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.

feat(chat): long text fields, custom sampling rows, Enter key setting, 375 px composer

purplecbded6df1b7a
diff --git a/e2e/input-and-persona-309.spec.ts b/e2e/input-and-persona-309.spec.ts
new file mode 100644
index 00000000..7393b782
--- /dev/null
+++ b/e2e/input-and-persona-309.spec.ts
@@ -0,0 +1,175 @@
+import { test, expect, type Page } from '@playwright/test'
+import { tauriMockInit, DEFAULT_MODEL_NAME, type TauriMockOptions } from './support/tauri-mock'
+import { seedOnboardingDone } from './support/cloud-mock'
+import { openNewChat } from './support/ui'
+
+/**
+ * LU 3.0.9, package P2 "input and persona":
+ *
+ * - GH #198: custom sampling rows of a persona and of a chat reach the
+ * request, top level on the OpenAI protocol and inside `options` on
+ * Ollama; the chat's row wins; in a group each member has its own.
+ * - GH #202: with "New line" Enter adds a line and Ctrl+Enter sends.
+ * - 375 px: Sampling, the model and Send stay in the frame, and the popup
+ * keeps off the right edge.
+ *
+ * Measured at the payload of each request.
+ *
+ * Run: CI=1 npx playwright test e2e/input-and-persona-309.spec.ts
+ */
+
+const FIRST = 'qwen3:4b'
+const SECOND = 'llama3.1:8b'
+
+const BARON = {
+ id: 'p-baron', name: 'Baron', icon: 'User', isBuiltIn: false, systemPrompt: 'You are Baron.',
+ customParams: [
+ { key: 'dry_base', type: 'number', value: '1.75' },
+ { key: 'dry_sequence_breakers', type: 'json', value: '["\\n", ":", "\\"", "*"]' },
+ { key: 'logit_bias', type: 'json', value: '{"128": -100}' },
+ ],
+}
+const WALT = {
+ id: 'p-walt', name: 'Walt', icon: 'User', isBuiltIn: false, systemPrompt: 'You are Walt.',
+ customParams: [{ key: 'xtc_probability', type: 'number', value: '0.9' }],
+}
+
+type WireBody = Record<string, unknown> & { model: string }
+
+async function chatBodies(page: Page): Promise<WireBody[]> {
+ const raw = await page.evaluate(() => {
+ const bodies: unknown = Reflect.get(window, '__E2E_CHAT_BODIES__')
+ return Array.isArray(bodies) ? bodies.map(String) : []
+ })
+ return raw.map((b) => JSON.parse(b) as WireBody).filter((b) => Array.isArray(b.messages))
+}
+
+async function seed(page: Page, personas: unknown[], settings: Record<string, unknown> = {}) {
+ await seedOnboardingDone(page)
+ await page.addInitScript(([list, extra]) => {
+ window.localStorage.setItem(
+ 'chat-settings',
+ JSON.stringify({
+ state: {
+ settings: { onboardingDone: true, appMode: 'local', personasEnabled: true, ...extra },
+ personas: list,
+ activePersonaId: 'unrestricted',
+ _version: 10,
+ },
+ version: 10,
+ }),
+ )
+ }, [personas, settings] as const)
+}
+
+async function send(page: Page, text: string) {
+ await page.evaluate(() => { Reflect.set(window, '__E2E_CHAT_BODIES__', []) })
+ await page.locator('textarea').first().fill(text)
+ await page.getByRole('button', { name: /Send message/i }).click()
+}
+
+async function addRow(page: Page, key: string, value: string) {
+ const panel = page.getByTestId('sampling-panel')
+ await panel.getByTestId('custom-param-add').click()
+ const row = panel.getByTestId('custom-param-row').last()
+ await row.getByLabel('Parameter name').fill(key)
+ await row.getByLabel('Parameter value').fill(value)
+}
+
+test('a persona\'s custom rows go out as typed, and a row in the chat wins', async ({ page }) => {
+ const opts: TauriMockOptions = { assistantReply: 'Hello.', modelName: DEFAULT_MODEL_NAME, platform: 'mac' }
+ await page.addInitScript(tauriMockInit, opts)
+ await seed(page, [BARON])
+ await page.goto('/')
+ await openNewChat(page)
+ await page.getByRole('button', { name: /Plugins/ }).click()
+ await page.getByRole('button', { name: /^Persona/ }).click()
+ await page.getByRole('button', { name: 'Baron', exact: true }).click()
+ await page.getByTitle('Enable persona for this chat').click()
+ await page.keyboard.press('Escape')
+
+ await send(page, 'hello')
+ await expect.poll(async () => (await chatBodies(page)).length, { timeout: 30_000 }).toBeGreaterThan(0)
+ let body = (await chatBodies(page))[0]
+ expect(body.dry_base).toBe(1.75)
+ expect(body.dry_sequence_breakers).toEqual(['\n', ':', '"', '*'])
+ expect(body.logit_bias).toEqual({ '128': -100 })
+
+ await expect(page.getByRole('button', { name: 'Regenerate response' })).toBeVisible({ timeout: 30_000 })
+ await page.getByTestId('sampling-trigger').click()
+ await expect(page.getByTestId('custom-params-inherited')).toContainText('dry_base')
+ await addRow(page, 'dry_base', '2')
+ await page.getByTestId('sampling-close').click()
+ await page.waitForTimeout(800)
+ await send(page, 'again')
+ await expect.poll(async () => (await chatBodies(page)).length, { timeout: 30_000 }).toBeGreaterThan(0)
+ body = (await chatBodies(page))[0]
+ expect(body.dry_base).toBe(2)
+ expect(body.logit_bias).toEqual({ '128': -100 })
+ expect(JSON.stringify(body).match(/"dry_base"/g)).toHaveLength(1)
+})
+
+test('in a group every member sends its own persona\'s rows, inside Ollama\'s options', async ({ page }) => {
+ const opts: TauriMockOptions = {
+ assistantReply: 'A short answer.', modelName: DEFAULT_MODEL_NAME, platform: 'mac', ollamaModels: [FIRST, SECOND],
+ }
+ await page.addInitScript(tauriMockInit, opts)
+ await seed(page, [BARON, WALT])
+ await page.goto('/')
+ await openNewChat(page)
+ await page.getByRole('button', { name: /Plugins/ }).click()
+ await page.getByRole('button', { name: /Group chat/ }).click()
+ for (const [model, persona] of [[FIRST, 'Baron'], [SECOND, 'Walt']] as const) {
+ const row = page.locator(`[data-testid="group-participant"][data-model="${model}"]`)
+ await row.getByRole('button').first().click()
+ await row.getByTestId('group-persona-trigger').click()
+ await row.getByTestId('group-persona-list').getByRole('button', { name: persona, exact: true }).click()
+ }
+ await page.keyboard.press('Escape')
+ await send(page, 'introduce yourselves')
+ await expect.poll(async () => (await chatBodies(page)).filter((b) => b.model === FIRST || b.model === SECOND).length, { timeout: 30_000 })
+ .toBe(2)
+ const bodies = await chatBodies(page)
+ const a = bodies.find((b) => b.model === FIRST)!.options as Record<string, unknown>
+ const b = bodies.find((x) => x.model === SECOND)!.options as Record<string, unknown>
+ expect(a.dry_base).toBe(1.75)
+ expect(a.xtc_probability).toBeUndefined()
+ expect(b.xtc_probability).toBe(0.9)
+ expect(b.dry_base).toBeUndefined()
+})
+
+test('"New line": Enter adds a line, Ctrl+Enter sends', async ({ page }) => {
+ await page.addInitScript(tauriMockInit, { assistantReply: 'Hi.', modelName: DEFAULT_MODEL_NAME, platform: 'windows' } as TauriMockOptions)
+ await seed(page, [], { enterKey: 'newline' })
+ await page.goto('/')
+ await openNewChat(page)
+ await page.evaluate(() => { Reflect.set(window, '__E2E_CHAT_BODIES__', []) })
+ const field = page.locator('textarea[data-lu-composer]')
+ await expect(field).toHaveAttribute('placeholder', 'Message... (Ctrl+Enter to send)')
+ await field.click()
+ await page.keyboard.type('first line')
+ await page.keyboard.press('Enter')
+ await page.keyboard.type('second line')
+ await page.waitForTimeout(500)
+ expect(await chatBodies(page)).toHaveLength(0)
+ await expect(field).toHaveValue('first line\nsecond line')
+ await page.keyboard.press('Control+Enter')
+ await expect.poll(async () => (await chatBodies(page)).length, { timeout: 30_000 }).toBeGreaterThan(0)
+})
+
+test('375 px: Sampling, the model and Send stay in the frame, the popup off the edge', async ({ page }) => {
+ await page.addInitScript(tauriMockInit, { assistantReply: 'Hi.', modelName: DEFAULT_MODEL_NAME, platform: 'mac' } as TauriMockOptions)
+ await seed(page, [])
+ await page.setViewportSize({ width: 375, height: 812 })
+ await page.goto('/')
+ await openNewChat(page)
+ for (const id of ['sampling-trigger', 'composer-send-slot']) {
+ const box = (await page.getByTestId(id).boundingBox())!
+ expect(box.x + box.width, id).toBeLessThanOrEqual(375)
+ }
+ await page.getByTestId('sampling-trigger').click()
+ await expect.poll(async () => {
+ const box = (await page.getByTestId('sampling-panel').boundingBox())!
+ return box.x + box.width
+ }).toBeLessThanOrEqual(371)
+})
diff --git a/src/api/providers/__tests__/custom-params-reach-the-body.test.ts b/src/api/providers/__tests__/custom-params-reach-the-body.test.ts
new file mode 100644
index 00000000..b579b836
--- /dev/null
+++ b/src/api/providers/__tests__/custom-params-reach-the-body.test.ts
@@ -0,0 +1,192 @@
+/**
+ * GH #198: custom sampling rows reach the request where the backend reads
+ * samplers, as typed, and never twice.
+ *
+ * - OpenAI compatible (bundled engine, own server, remote endpoint): top
+ * level of the body, under the name typed.
+ * - Ollama: inside `options`.
+ * - LU Cloud and Anthropic: none.
+ * - A key LU sets from its own field (temperature, top_p, num_ctx ...) never
+ * comes from a row, so the body holds it once, with the field's value.
+ *
+ * The values are the examples from the issue.
+ *
+ * Run: npx vitest run src/api/providers/__tests__/custom-params-reach-the-body.test.ts
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import type { ProviderConfig, ChatStreamChunk, ChatOptions } from '../types'
+import type { FetchArgs } from '../../__tests__/provider-test-support'
+
+const streamBody = 'data: {"choices":[{"delta":{"content":"hi"}}]}\n\ndata: [DONE]\n\n'
+
+type CapturedInit = { body?: string }
+type Body = Record<string, unknown>
+
+let sent: { url: string; body: Body }[]
+
+function answer(url: string, init: CapturedInit) {
+ if (typeof init.body !== 'string') throw new Error('request had no JSON body')
+ const body = JSON.parse(init.body) as Body
+ sent.push({ url, body })
+ if (body.stream) return new Response(streamBody, { status: 200 })
+ return new Response(JSON.stringify({ choices: [{ message: { content: 'ok' } }] }), { status: 200 })
+}
+
+async function makeOpenAI(config: ProviderConfig) {
+ vi.resetModules()
+ sent = []
+ vi.doMock('../../backend', () => ({
+ localFetch: vi.fn(async (url: string, init: CapturedInit) => answer(url, init)),
+ localFetchStream: vi.fn(async (url: string, init: CapturedInit) => answer(url, init)),
+ backendCall: vi.fn(),
+ isPrivateOrLanHost: (host: string) => host === 'localhost' || host === '127.0.0.1',
+ isDirectFetchAllowed: () => true,
+ hostnameOf: (url: string) => new URL(url).hostname,
+ ensureProxyAllowsHost: vi.fn(),
+ isTauri: () => false,
+ }))
+ vi.doMock('../../builtin-ensure', () => ({
+ ensureBuiltinEngineAlive: vi.fn(),
+ explainDeadEngine: (e: unknown) => e,
+ explainEngineTransportMessage: (m: string) => m,
+ isManagedBuiltinSlot: () => false,
+ }))
+ const mod = await import('../openai-provider')
+ return new mod.OpenAIProvider(config)
+}
+
+async function drain(gen: AsyncGenerator<ChatStreamChunk>) {
+ for await (const _ of gen) { /* the fetch only fires on the first next() */ }
+}
+
+const chatBody = () => {
+ const hit = sent.find((s) => s.url.endsWith('/chat/completions'))
+ if (!hit) throw new Error('no chat request was sent')
+ return hit.body
+}
+
+const ISSUE_ROWS: Record<string, unknown> = {
+ dry_base: 1.75,
+ dry_allowed_length: 4,
+ dry_penalty_last_n: -1,
+ dry_sequence_breakers: ['\n', ':', '"', '*'],
+ xtc_threshold: 0.1,
+ xtc_probability: 0.5,
+ banned_strings: ['ministrations', 'shivers down'],
+ logit_bias: { '128': -100 },
+}
+
+const WITH_ROWS: ChatOptions = { temperature: 0.8, customParams: { ...ISSUE_ROWS, temperature: 1.4, top_p: 0.1, num_ctx: 999, model: 'other', messages: [] } }
+
+const ENGINE: ProviderConfig = {
+ id: 'openai', name: 'LU Engine', apiKey: '', enabled: true,
+ baseUrl: 'http://127.0.0.1:8127/v1', isLocal: true, managed: true,
+}
+const LM_STUDIO: ProviderConfig = {
+ id: 'openai', name: 'LM Studio', apiKey: '', enabled: true,
+ baseUrl: 'http://localhost:1234/v1', isLocal: true,
+}
+const REMOTE: ProviderConfig = {
+ id: 'openai', name: 'OpenAI', apiKey: 'sk-test', enabled: true,
+ baseUrl: 'https://api.openai.com/v1', isLocal: false,
+}
+const HOSTED: ProviderConfig = {
+ id: 'lu-cloud', name: 'Hosted', apiKey: 'tok', enabled: true,
+ baseUrl: 'https://lu-labs.ai/api/inference/v1', isLocal: false,
+}
+
+beforeEach(() => {
+ vi.spyOn(globalThis, 'fetch').mockImplementation(
+ async (url: FetchArgs[0], init: FetchArgs[1]) =>
+ answer(String(url), { body: typeof init?.body === 'string' ? init.body : undefined }),
+ )
+})
+afterEach(() => {
+ vi.doUnmock('../../backend')
+ vi.doUnmock('../../builtin-ensure')
+ vi.restoreAllMocks()
+ vi.resetModules()
+})
+
+describe('OpenAI compatible', () => {
+ for (const [name, config] of [['bundled engine', ENGINE], ['own server', LM_STUDIO], ['remote endpoint', REMOTE]] as const) {
+ it(`${name}: every row at the top level, as typed`, async () => {
+ const p = await makeOpenAI(config)
+ await drain(p.chatStream('m', [{ role: 'user', content: 'hi' }], WITH_ROWS))
+ const body = chatBody()
+ for (const [key, value] of Object.entries(ISSUE_ROWS)) expect(body[key], key).toEqual(value)
+ })
+ }
+
+ it('a fixed field is never taken from a row: the field wins, once', async () => {
+ const p = await makeOpenAI(LM_STUDIO)
+ await drain(p.chatStream('m', [{ role: 'user', content: 'hi' }], WITH_ROWS))
+ const raw = JSON.stringify(chatBody())
+ const body = chatBody()
+ expect(body.temperature).toBe(0.8)
+ expect(raw.match(/"temperature"/g)).toHaveLength(1)
+ expect('top_p' in body).toBe(false)
+ expect('num_ctx' in body).toBe(true) // not an OpenAI field LU writes: it goes as typed
+ expect(body.model).toBe('m')
+ expect(Array.isArray(body.messages) && body.messages.length).toBe(1)
+ })
+
+ it('the tool path carries them too', async () => {
+ const p = await makeOpenAI(LM_STUDIO)
+ await p.chatWithTools('m', [{ role: 'user', content: 'hi' }], [], WITH_ROWS)
+ expect(chatBody().xtc_threshold).toBe(0.1)
+ })
+
+ it('LU Cloud gets none', async () => {
+ const p = await makeOpenAI(HOSTED)
+ await drain(p.chatStream('m', [{ role: 'user', content: 'hi' }], WITH_ROWS))
+ const body = chatBody()
+ for (const key of Object.keys(ISSUE_ROWS)) expect(key in body, key).toBe(false)
+ })
+
+ it('NEGATIVKONTROLLE: no rows, no extra fields', async () => {
+ const p = await makeOpenAI(LM_STUDIO)
+ await drain(p.chatStream('m', [{ role: 'user', content: 'hi' }], { temperature: 0.8 }))
+ const body = chatBody()
+ for (const key of Object.keys(ISSUE_ROWS)) expect(key in body, key).toBe(false)
+ })
+})
+
+describe('Ollama', () => {
+ it('every row inside options, never at the top level; num_ctx stays LU\'s', async () => {
+ vi.resetModules()
+ const bodies: Body[] = []
+ const reply = (_url: string, init?: { body?: unknown }) => {
+ if (typeof init?.body === 'string') bodies.push(JSON.parse(init.body) as Body)
+ return new Response(
+ JSON.stringify({ message: { content: 'ok' }, done: true, done_reason: 'stop' }) + '\n',
+ { status: 200 },
+ )
+ }
+ vi.doMock('../../backend', () => ({
+ isTauri: () => false,
+ localFetch: vi.fn(async (url: string, init?: { body?: unknown }) => reply(url, init)),
+ localFetchStream: vi.fn(async (url: string, init?: { body?: unknown }) => reply(url, init)),
+ ollamaUrl: (path: string) => `/api${path}`,
+ }))
+ const { OllamaProvider } = await import('../ollama-provider')
+ const p = new OllamaProvider({
+ id: 'ollama', name: 'Ollama', enabled: true, baseUrl: 'http://localhost:11434', apiKey: '', isLocal: true,
+ })
+ await drain(p.chatStream('gemma3:4b', [{ role: 'user', content: 'hi' }], WITH_ROWS))
+ await p.chatWithTools('gemma3:4b', [{ role: 'user', content: 'hi' }], [], WITH_ROWS)
+ const chats = bodies.filter((b) => Array.isArray(b.messages))
+ expect(chats).toHaveLength(2)
+ for (const chat of chats) {
+ const options = chat.options as Record<string, unknown>
+ for (const [key, value] of Object.entries(ISSUE_ROWS)) {
+ expect(options[key], key).toEqual(value)
+ expect(key in chat, `${key} at the top level`).toBe(false)
+ }
+ expect(options.temperature).toBe(0.8)
+ expect(options.top_p).toBeUndefined()
+ expect(options.num_ctx).not.toBe(999)
+ expect(chat.model).toBe('gemma3:4b')
+ }
+ })
+})
diff --git a/src/api/providers/ollama-provider.ts b/src/api/providers/ollama-provider.ts
index e6c323eb..149c2e26 100644
--- a/src/api/providers/ollama-provider.ts
+++ b/src/api/providers/ollama-provider.ts
@@ -1,5 +1,6 @@
import { chatBackendsBack } from '../../lib/chat-backends-gate'
import { ollamaSamplerOptions } from './sampler-fields'
+import { ollamaCustomOptions } from '../../lib/custom-params'
import { resolveMessageAttachments } from '../../lib/chat-attachments'
/**
* Ollama Provider, wraps existing ollama.ts into the ProviderClient interface.
@@ -45,6 +46,8 @@ export interface OllamaRequestOptions {
repeat_penalty?: number
presence_penalty?: number
frequency_penalty?: number
+ /** GH #198: custom rows (dry_base, xtc_threshold ...), see lib/custom-params.ts. */
+ [custom: string]: unknown
}
export interface OllamaRequestMessage {
@@ -168,6 +171,8 @@ export class OllamaProvider implements ProviderClient {
if (options?.topK !== undefined) ollamaOptions.top_k = options.topK
if (options?.maxTokens && options.maxTokens > 0) ollamaOptions.num_predict = options.maxTokens
if (options) Object.assign(ollamaOptions, ollamaSamplerOptions(options))
+ // GH #198: the custom rows, inside options, where Ollama reads samplers.
+ Object.assign(ollamaOptions, ollamaCustomOptions(options?.customParams))
// The window: resolved in ONE place for every request to Ollama, so the
// model is never loaded again by a call that sends another one. Without
// any, Ollama runs at its own small default and cuts real chats short.
@@ -332,6 +337,8 @@ export class OllamaProvider implements ProviderClient {
if (options?.topK !== undefined) ollamaOptions.top_k = options.topK
if (options?.maxTokens && options.maxTokens > 0) ollamaOptions.num_predict = options.maxTokens
if (options) Object.assign(ollamaOptions, ollamaSamplerOptions(options))
+ // GH #198: the custom rows, inside options, where Ollama reads samplers.
+ Object.assign(ollamaOptions, ollamaCustomOptions(options?.customParams))
// The window, see chatStream().
Object.assign(ollamaOptions, await ollamaWindowOption(model, options?.window))
body.options = ollamaOptions
diff --git a/src/api/providers/openai-provider.ts b/src/api/providers/openai-provider.ts
index bd436970..72004fa4 100644
--- a/src/api/providers/openai-provider.ts
+++ b/src/api/providers/openai-provider.ts
@@ -29,6 +29,7 @@ import { requestLimitMessage } from '../../lib/request-limit'
import { localFetch, localFetchStream, isPrivateOrLanHost, isDirectFetchAllowed, hostnameOf, ensureProxyAllowsHost, backendCall } from '../backend'
import { chatBackendsBack } from '../../lib/chat-backends-gate'
import { openAiSamplerFields } from './sampler-fields'
+import { openAiCustomFields } from '../../lib/custom-params'
import { topPForTemperature } from '../../lib/sampling'
import { ensureBuiltinEngineAlive, explainDeadEngine, explainEngineTransportMessage, isManagedBuiltinSlot } from '../builtin-ensure'
import { isLocalTransportFailure, localBackendUnreachableMessage, remoteBackendUnreachableMessage } from '../../lib/local-backend-transport'
@@ -707,6 +708,18 @@ export class OpenAIProvider implements ProviderClient {
* other server in this slot is a version we do not know, and the cloud
* endpoints refuse unknown fields, so nobody else gets it.
*/
+ /**
+ * GH #198: the custom sampling rows of the persona and the chat, as top
+ * level fields, under the names typed. A field LU sets itself is never
+ * taken from a row (lib/custom-params.ts). Not for LU Cloud, whose proxy
+ * refuses a field it does not know. A strict remote server may refuse one
+ * too; the person added the row for that server and sees its answer.
+ */
+ private applyCustomParams(body: OpenAIChatRequest, options?: ChatOptions): void {
+ if (this.config.id === 'lu-cloud') return
+ Object.assign(body, openAiCustomFields(options?.customParams))
+ }
+
private applyThinkBudget(body: OpenAIChatRequest, options?: ChatOptions): void {
if (this.config.managed !== true) return
const budget = thinkBudgetForRequest(options?.thinking, options?.thinkingBudget)
@@ -1029,6 +1042,7 @@ export class OpenAIProvider implements ProviderClient {
// server on this machine or the LAN counts as local whether its preset
// said so or only its address does, an additional entry (#173) included.
if (options) Object.assign(body, openAiSamplerFields(this.samplerTarget, options))
+ this.applyCustomParams(body, options)
// Streaming tool turn: same wire shape as chatWithTools, but the calls
// come back as deltas which the accumulator below already merges.
if (options?.tools?.length) {
@@ -1284,6 +1298,7 @@ export class OpenAIProvider implements ProviderClient {
if (options?.topK !== undefined && this.config.id !== 'lu-cloud') body.top_k = options.topK
// GH #175: the extra samplers, under the names this backend reads.
if (options) Object.assign(body, openAiSamplerFields(this.samplerTarget, options))
+ this.applyCustomParams(body, options)
await this.applyMaxTokens(model, body, options)
// Same reasoning_effort gate as chatStream.
const effort = this.thinkingEffort(model, options?.thinking, options)
diff --git a/src/api/providers/types.ts b/src/api/providers/types.ts
index da128fc0..c7e674d7 100644
--- a/src/api/providers/types.ts
+++ b/src/api/providers/types.ts
@@ -236,6 +236,11 @@ export interface ChatOptions {
presencePenalty?: number
frequencyPenalty?: number
dryMultiplier?: number
+ /** GH #198: custom sampling parameters, key → parsed value. OpenAI
+ * compatible providers put them at the top level of the body, Ollama in
+ * `options`; a key LU sets from its own field is never taken from here
+ * (lib/custom-params.ts). */
+ customParams?: Record<string, unknown>
/**
* True when `maxTokens` above is THIS caller's own fallback default, not a
* value the user actually typed into a slider (bau/wfprogress.md Runde 3,
diff --git a/src/components/__tests__/fokusring-und-press.test.ts b/src/components/__tests__/fokusring-und-press.test.ts
index ffa93046..935afb80 100644
--- a/src/components/__tests__/fokusring-und-press.test.ts
+++ b/src/components/__tests__/fokusring-und-press.test.ts
@@ -300,6 +300,9 @@ describe('Punkt 4 — die Ausnahme steht AN der Regel, nicht gegen sie', () => {
const AM_KASTEN: Record<string, string> = {
'chat/ChatInput.tsx': 'chat/ChatInput.tsx',
'create/ui/PromptField.tsx': 'create/experimental/Composer.tsx',
+ // GH #197: the search box and the text of the large editor, each in a
+ // box with focus-within:border-.
+ 'ui/LongTextField.tsx': 'ui/LongTextField.tsx',
}
it('`lu-fokus-am-kasten` haengt an genau diesen Feldern und sonst nirgends', () => {
diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsx
index 5f45c6ce..d8c30fe5 100644
--- a/src/components/chat/ChatInput.tsx
+++ b/src/components/chat/ChatInput.tsx
@@ -10,6 +10,8 @@ import { ComputerNote } from '../computer/ComputerNote'
import { dismissComputerStop } from '../../api/computer-use'
import { useVoiceStore } from '../../stores/voiceStore'
import { useSettingsStore } from '../../stores/settingsStore'
+import { composerHint, composerPlaceholder, composerSends, enterKeyMode } from '../../lib/enter-key'
+import { isMacOS } from '../../lib/device-kind'
import { useUIStore } from '../../stores/uiStore'
import { useModelStore } from '../../stores/modelStore'
import { useChatStore } from '../../stores/chatStore'
@@ -288,6 +290,8 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
const updateSettings = useSettingsStore((s) => s.updateSettings)
// Emoticons to emojis while typing (lib/emoticons.ts, Settings: Appearance).
const emojiOn = useSettingsStore((s) => s.settings.emojiAutoReplace) !== false
+ // GH #202: whether Enter sends or adds a line.
+ const enterMode = enterKeyMode(useSettingsStore((s) => s.settings.enterKey))
// The last turn, for one Backspace to take back, and the caret it leaves.
const emojiTurnRef = useRef<EmojiTurn | null>(null)
const caretRef = useRef<number | null>(null)
@@ -674,7 +678,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
return
}
}
- if (e.key === 'Enter' && !e.shiftKey) {
+ if (composerSends({ key: e.key, shiftKey: e.shiftKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, altKey: e.altKey, isComposing: e.nativeEvent.isComposing }, enterMode)) {
e.preventDefault()
// While the last words are still being transcribed, Enter waits for
// them. While recording it sends what the field shows and ends the
@@ -901,7 +905,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
onKeyDown={handleKeyDown}
onBlur={() => setTimeout(() => setCmdMenu([]), 120)}
onPaste={handlePaste}
- placeholder={disabled ? "Unavailable" : isDragOver ? "Drop files here..." : isTranscribing ? "Transcribing..." : isVoiceRecording ? "Recording..." : "Message..."}
+ placeholder={disabled ? "Unavailable" : isDragOver ? "Drop files here..." : isTranscribing ? "Transcribing..." : isVoiceRecording ? "Recording..." : composerPlaceholder(enterMode, isMacOS())}
disabled={disabled}
rows={1}
className="lu-fokus-am-kasten w-full bg-transparent resize-none text-gray-800 dark:text-gray-200 placeholder-gray-400 dark:placeholder-gray-600 focus:outline-none text-[12px] leading-relaxed max-h-[200px] disabled:opacity-50 scrollbar-thin"
@@ -923,7 +927,17 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
only the middle spacer giving way, das `flex: 0 0 auto` steckt
seit der Composer-Grammatik im Rezept `.lu-control` (index.css),
nicht mehr als `shrink-0` an jedem einzelnen Knopf. */}
- <div className="@container flex flex-nowrap items-center gap-1 px-2 py-1.5 min-h-[38px] border-t border-gray-200 dark:border-white/[0.05]">
+ {/* Narrow (a phone-wide window, 375 px with the rail open): the row
+ had 470 px of controls in 253, and Sampling, the model and Send
+ were pushed out past the right edge. Below 26rem the labels of
+ Docs, Plugins and Effort shrink to their icons, and Sampling, the
+ model and Send move to a second line of their own. That line is
+ there by WIDTH alone, never by what is running, so the composer
+ still keeps one height while it works (see below). */}
+ {/* The query container sits one level out: a container query cannot
+ style the container itself, and the row has to wrap. */}
+ <div className="@container">
+ <div className="flex flex-nowrap items-center gap-1 px-2 py-1.5 min-h-[38px] border-t border-gray-200 dark:border-white/[0.05] @max-[26rem]:flex-wrap">
{/* Clip button */}
<button
onClick={() => fileInputRef.current?.click()}
@@ -1008,7 +1022,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
title={effortHint}
>
<Gauge size={11} />
- <span>{effortText}</span>
+ <span className="@max-[26rem]:sr-only">{effortText}</span>
</button>
)}
{showEffortGreyed && (
@@ -1020,7 +1034,7 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
title={`Reasoning effort: ${effortNote}`}
>
<Gauge size={11} />
- <span>Effort</span>
+ <span className="@max-[26rem]:sr-only">Effort</span>
</button>
)}
@@ -1051,6 +1065,10 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
<div className="flex-1 min-w-0" />
+ {/* The right cluster. `contents` in a wide row, so the controls sit
+ in the one row exactly as before; in a narrow one its own full
+ width line, right aligned. */}
+ <div className="contents @max-[26rem]:flex @max-[26rem]:basis-full @max-[26rem]:min-w-0 @max-[26rem]:items-center @max-[26rem]:justify-end @max-[26rem]:gap-1" data-testid="composer-right-cluster">
{/* Sampling controls sit next to the picker: same row, collapsed. */}
<div className="shrink-0"><SamplingControls /></div>
@@ -1091,11 +1109,14 @@ export function ChatInput({ onSend, onStop, isGenerating, waitingForLocalLane, p
disabled={preparingImages || preparingFiles || (!input.trim() && images.length === 0 && files.length === 0 && media.length === 0) || isTranscribing || !!waitingForLocalLane}
className="lu-control lu-control--icon lu-primary w-full h-full"
aria-label="Send message"
+ title={composerHint(enterMode, isMacOS())}
>
<Send size={13} />
</button>
)}
</div>
+ </div>
+ </div>
</div>
</div>
</div>
diff --git a/src/components/chat/CustomParamsEditor.tsx b/src/components/chat/CustomParamsEditor.tsx
new file mode 100644
index 00000000..90d81ed4
--- /dev/null
+++ b/src/components/chat/CustomParamsEditor.tsx
@@ -0,0 +1,126 @@
+import { Plus, X } from 'lucide-react'
+import { HINWEIS_TEXT } from '../../lib/hinweis'
+import {
+ CUSTOM_PARAM_TYPES, MAX_CUSTOM_PARAMS, customParamProblem,
+ type CustomParam, type CustomParamType,
+} from '../../lib/custom-params'
+
+/** Accessible name of the list, shared with its tests. */
+export const CUSTOM_PARAMS_LABEL = 'Custom parameters'
+
+/** Where the rows go, said once under the list. */
+export const CUSTOM_PARAMS_HINT =
+ 'Sent as typed: top level for OpenAI compatible servers, inside "options" for Ollama. '
+ + 'Not sent to Anthropic or LU Cloud.'
+
+const PLACEHOLDER: Record<CustomParamType, string> = {
+ string: 'text',
+ number: '1.75',
+ boolean: 'true',
+ json: '["\\n", ":", "\\"", "*"]',
+}
+
+/**
+ * GH #198: the rows of custom sampling parameters, key, type and value, in
+ * the persona editor and in the chat's Sampling popup. Narrow on purpose: the
+ * popup is 248 px wide, so the value has a line of its own.
+ */
+export function CustomParamsEditor({
+ rows,
+ onChange,
+ inherited,
+ testId = 'custom-params',
+}: {
+ rows: readonly CustomParam[]
+ onChange: (rows: CustomParam[]) => void
+ /** Keys that come from somewhere below (the persona), shown as a line. */
+ inherited?: { source: string; rows: readonly CustomParam[] }
+ testId?: string
+}) {
+ const update = (i: number, patch: Partial<CustomParam>) =>
+ onChange(rows.map((r, j) => (j === i ? { ...r, ...patch } : r)))
+ const remove = (i: number) => onChange(rows.filter((_, j) => j !== i))
+ const add = () => onChange([...rows, { key: '', type: 'number', value: '' }])
+ const own = new Set(rows.map((r) => r.key.trim()))
+ const below = (inherited?.rows ?? []).filter((r) => r.key.trim() && !own.has(r.key.trim()))
+
+ return (
+ <div role="group" aria-label={CUSTOM_PARAMS_LABEL} data-testid={testId} className="space-y-1.5">
+ {rows.map((row, i) => {
+ const problem = customParamProblem(row)
+ return (
+ <div key={i} data-testid="custom-param-row" className="space-y-0.5">
+ <div className="flex items-center gap-1">
+ <input
+ value={row.key}
+ onChange={(e) => update(i, { key: e.target.value })}
+ placeholder="dry_base"
+ aria-label="Parameter name"
+ spellCheck={false}
+ className="min-w-0 flex-1 rounded border border-gray-700 bg-transparent px-1 py-0.5 font-mono"
+ />
+ <select
+ value={row.type}
+ onChange={(e) => update(i, { type: e.target.value as CustomParamType })}
+ aria-label="Parameter type"
+ className="w-[4.5rem] shrink-0 rounded border border-gray-700 bg-transparent px-0.5 py-0.5"
+ >
+ {CUSTOM_PARAM_TYPES.map((t) => (
+ <option key={t} value={t}>{t === 'json' ? 'JSON' : t}</option>
+ ))}
+ </select>
+ <button
+ type="button"
+ onClick={() => remove(i)}
+ aria-label={`Remove ${row.key.trim() || 'parameter'}`}
+ className="shrink-0 rounded p-0.5 text-gray-500 hover:text-gray-300"
+ >
+ <X size={11} />
+ </button>
+ </div>
+ {row.type === 'boolean' ? (
+ <select
+ value={row.value === 'false' ? 'false' : row.value === 'true' ? 'true' : ''}
+ onChange={(e) => update(i, { value: e.target.value })}
+ aria-label="Parameter value"
+ className="w-full rounded border border-gray-700 bg-transparent px-0.5 py-0.5"
+ >
+ <option value="" disabled>choose</option>
+ <option value="true">true</option>
+ <option value="false">false</option>
+ </select>
+ ) : (
+ <input
+ value={row.value}
+ onChange={(e) => update(i, { value: e.target.value })}
+ placeholder={PLACEHOLDER[row.type]}
+ aria-label="Parameter value"
+ spellCheck={false}
+ inputMode={row.type === 'number' ? 'decimal' : undefined}
+ className="w-full rounded border border-gray-700 bg-transparent px-1 py-0.5 font-mono"
+ />
+ )}
+ {problem && (
+ <p className={HINWEIS_TEXT.fehler} data-testid="custom-param-problem">{problem} Not sent.</p>
+ )}
+ </div>
+ )
+ })}
+ {below.length > 0 && inherited && (
+ <p className="text-gray-500 break-words" data-testid="custom-params-inherited">
+ From {inherited.source}: {below.map((r) => r.key.trim()).join(', ')}
+ </p>
+ )}
+ <button
+ type="button"
+ onClick={add}
+ disabled={rows.length >= MAX_CUSTOM_PARAMS}
+ data-testid="custom-param-add"
+ className="flex items-center gap-1 text-gray-400 hover:text-gray-200 disabled:opacity-40"
+ >
+ <Plus size={11} /> Add parameter
+ </button>
+ <p className="text-gray-500">{CUSTOM_PARAMS_HINT}</p>
+ </div>
+ )
+}
diff --git a/src/components/chat/DocsButton.tsx b/src/components/chat/DocsButton.tsx
index 5de0f66c..c9bb8594 100644
--- a/src/components/chat/DocsButton.tsx
+++ b/src/components/chat/DocsButton.tsx
@@ -41,7 +41,9 @@ export function DocsButton({ availability, open, ragEnabled, docCount, onToggle
className={'lu-control' + (availability.needsSetup ? ' opacity-60' : '')}
>
<FileText size={11} />
- <span>Docs</span>
+ {/* In a narrow composer only the icon shows; the name stays for the
+ screen reader (ChatInput.tsx, the row is the @container). */}
+ <span className="@max-[26rem]:sr-only">Docs</span>
{docCount > 0 && (
<span
className={
diff --git a/src/components/chat/MemoryDebugPanel.tsx b/src/components/chat/MemoryDebugPanel.tsx
index 22f696e8..3a9d2c36 100644
--- a/src/components/chat/MemoryDebugPanel.tsx
+++ b/src/components/chat/MemoryDebugPanel.tsx
@@ -7,6 +7,7 @@ import { useModelStore } from '../../stores/modelStore'
import { getModelMaxTokens } from '../../lib/context-compaction'
import { AnimatePresence, motion } from 'framer-motion'
import { MemoryDeleteConfirm, MemoryRowDelete, MemoryUndoBar, memoriesWord, useMemoryUndo } from './MemoryDelete'
+import { LongTextField } from '../ui/LongTextField'
// Memory button. Lives in the TOP BAR next to the model picker (the owner
// 2026-06-06: "memory button raus aus chat/code/agent, neben den modelloader
@@ -206,12 +207,14 @@ function MemoryPopover({ onClose }: { onClose: () => void }) {
placeholder="Title (optional)"
className="w-full px-2 py-1 rounded bg-black/20 border border-white/10 t-micro text-gray-200 placeholder-gray-600 focus:outline-none focus:border-purple-500/40"
/>
- <textarea
+ <LongTextField
value={newContent}
- onChange={(e) => setNewContent(e.target.value)}
+ onChange={setNewContent}
+ storageKey="memory-content"
+ label="Memory"
placeholder="What should the model always remember? (injected into every prompt)"
rows={3}
- className="w-full px-2 py-1 rounded bg-black/20 border border-white/10 t-micro text-gray-200 placeholder-gray-600 focus:outline-none focus:border-purple-500/40 resize-none"
+ className="block w-full px-2 py-1 rounded bg-black/20 border border-white/10 t-micro text-gray-200 placeholder-gray-600 focus:outline-none focus:border-purple-500/40"
/>
<div className="flex justify-end gap-1.5">
<button onClick={() => { setAdding(false); setNewTitle(''); setNewContent('') }} className="px-2 py-1 rounded t-micro text-gray-400 hover:text-gray-200 hover:bg-white/10">Cancel</button>
diff --git a/src/components/chat/MessageBubble.tsx b/src/components/chat/MessageBubble.tsx
index 06512ec7..394cfca1 100644
--- a/src/components/chat/MessageBubble.tsx
+++ b/src/components/chat/MessageBubble.tsx
@@ -38,6 +38,8 @@ import { RefusalNotice } from './RefusalNotice'
import { RequestUsageLine } from './RequestUsageLine'
import { fitTextarea } from '../../lib/fit-textarea'
import { editableText } from '../../lib/message-edit'
+import { editKeyAction, editShortcuts, enterKeyMode } from '../../lib/enter-key'
+import { isMacOS } from '../../lib/device-kind'
import { ForkSwitcher } from './ForkSwitcher'
interface Props {
@@ -106,6 +108,9 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, o
)
const toggleAgentMode = useAgentModeStore((s) => s.toggleAgentMode)
const userAvatarDataUrl = useSettingsStore((s) => s.settings.userAvatarDataUrl)
+ // GH #202: the Enter key in the edit field follows the same setting as the composer.
+ const enterMode = enterKeyMode(useSettingsStore((s) => s.settings.enterKey))
+ const editKeys = editShortcuts(enterMode, isMacOS())
// Chat Tools (v2.5.3) gives plain chat web/file/image/video WITHOUT Agent Mode.
// When it's on, the "turn Agent Mode on" banners below are wrong + contradictory
// (the tool IS available in normal chat) — they predate Chat Tools and only
@@ -511,10 +516,12 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, o
onKeyDown={(e) => {
// Enter saves, Ctrl or Cmd with Enter resends, Shift with
// Enter is a new line. Enter used to resend and drop every
- // later turn (GH #172).
- if (e.key === 'Enter' && !e.shiftKey) {
+ // later turn (GH #172). GH #202: in "new line" mode Enter is a
+ // line, Ctrl/Cmd+Enter saves and with Shift resends.
+ const action = editKeyAction({ key: e.key, shiftKey: e.shiftKey, ctrlKey: e.ctrlKey, metaKey: e.metaKey, altKey: e.altKey, isComposing: e.nativeEvent.isComposing }, enterMode)
+ if (action !== 'none') {
e.preventDefault()
- if ((e.ctrlKey || e.metaKey) && isUser && onEdit) resendEdit()
+ if (action === 'resend' && isUser && onEdit) resendEdit()
else saveEdit()
}
if (e.key === 'Escape') cancelEdit()
@@ -523,10 +530,11 @@ function MessageBubbleImpl({ message, onRegenerate, onEdit, pendingApprovalId, o
className="w-full bg-transparent text-[0.78rem] leading-relaxed text-gray-800 dark:text-gray-200 resize-none focus:outline-none"
/>
<div className="flex items-center gap-1 justify-end t-micro">
+ <span className="mr-auto text-gray-500" data-testid="edit-key-hint">{editKeys.hint}</span>
<button onClick={cancelEdit} className="px-1.5 py-0.5 rounded text-gray-500 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-white/10 transition-colors">Cancel</button>
- <button onClick={saveEdit} title="Change the text only (Enter)" className="px-1.5 py-0.5 rounded text-gray-700 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-white/10 transition-colors">Save</button>
+ <button onClick={saveEdit} title={`Change the text only (${editKeys.save})`} className="px-1.5 py-0.5 rounded text-gray-700 dark:text-gray-200 hover:bg-gray-200 dark:hover:bg-white/10 transition-colors">Save</button>
{isUser && onEdit && (
- <button onClick={resendEdit} title="Ask again from here and keep the current answers as a version (Ctrl+Enter)" className="px-1.5 py-0.5 rounded border border-gray-300 dark:border-white/15 text-gray-800 dark:text-gray-100 hover:bg-gray-200 dark:hover:bg-white/10 transition-colors">Save &amp; resend</button>
+ <button onClick={resendEdit} title={`Ask again from here and keep the current answers as a version (${editKeys.resend})`} className="px-1.5 py-0.5 rounded border border-gray-300 dark:border-white/15 text-gray-800 dark:text-gray-100 hover:bg-gray-200 dark:hover:bg-white/10 transition-colors">Save &amp; resend</button>
)}
</div>
</div>
diff --git a/src/components/chat/PluginsDropdown.tsx b/src/components/chat/PluginsDropdown.tsx
index 00fa9aff..f88a87ab 100644
--- a/src/components/chat/PluginsDropdown.tsx
+++ b/src/components/chat/PluginsDropdown.tsx
@@ -168,7 +168,7 @@ export function PluginsDropdown({
className="lu-control"
>
<Plug size={10} />
- <span>Plugins</span>
+ <span className="@max-[26rem]:sr-only">Plugins</span>
{anyPluginActive && (
<div className="flex gap-0.5">
{createOn && <div data-testid="plugins-dot-create" className="w-1 h-1 rounded-full bg-lu-accent" />}
diff --git a/src/components/chat/SamplingControls.tsx b/src/components/chat/SamplingControls.tsx
index 6c065d7b..9155eedb 100644
--- a/src/components/chat/SamplingControls.tsx
+++ b/src/components/chat/SamplingControls.tsx
@@ -10,6 +10,7 @@ import { SAMPLING_DEFAULTS, TEMPERATURE_MAX, AGENT_TEMPERATURE_MAX, TEMPERATURE_
import { resetTemperatureToDefault } from '../../lib/temperature-reset'
import { HighTemperatureWarning } from './HighTemperatureWarning'
import { HelpMark } from '../ui/HelpMark'
+import { CustomParamsEditor, CUSTOM_PARAMS_LABEL } from './CustomParamsEditor'
import type { SamplingOverrides } from '../../lib/sampling'
import { isGroupChat } from '../../lib/group-chat'
import { speakerSamplingLines, type SpeakerSamplingLine } from '../../lib/speaker-sampling-lines'
@@ -167,7 +168,7 @@ export function SamplingControls() {
const [draft, setDraft] = useState<string | null>(null)
const wrapRef = useRef<HTMLDivElement>(null)
const panelRef = useRef<HTMLDivElement>(null)
- const lage = usePopoverPlatz(panelRef, open, { bevorzugt: 'oben', abstand: 6 })
+ const lage = usePopoverPlatz(panelRef, open, { bevorzugt: 'oben', abstand: 6, breiteDeckeln: true })
const panelId = useId()
const settings = useSettingsStore((s) => s.settings)
const activeId = useChatStore((s) => s.activeConversationId)
@@ -179,6 +180,13 @@ export function SamplingControls() {
: undefined
)
const setSampling = useChatStore((s) => s.setConversationSampling)
+ // GH #198: this chat's own custom rows.
+ const customRows = useChatStore((s) =>
+ s.activeConversationId
+ ? s.conversations.find((c) => c.id === s.activeConversationId)?.customParams
+ : undefined
+ )
+ const setCustomRows = useChatStore((s) => s.setConversationCustomParams)
const agentMode = useAgentModeStore((s) => (activeId ? s.agentModeActive[activeId] === true : false))
const resetSampling = useChatStore((s) => s.resetConversationSampling)
// GH #175: who speaks in this chat, and which persona preset holds for
@@ -197,7 +205,7 @@ export function SamplingControls() {
useProviderStore((s) => s.openaiEntries)
const lines: SpeakerSamplingLine[] = speakerSamplingLines({
settings,
- conv: { personaId, systemPrompt: keptPrompt, personaEnabled, groupModels, groupPersonas, sampling: overrides },
+ conv: { personaId, systemPrompt: keptPrompt, personaEnabled, groupModels, groupPersonas, sampling: overrides, customParams: customRows },
activeModel,
personas,
activePersonaId,
@@ -212,13 +220,13 @@ export function SamplingControls() {
const sliderPreset = isGroupChat(groupModels) ? undefined : lines[0]?.preset
const value = effectiveSampling(settings, overrides, sliderPreset)
- const changed = samplingIsChanged(settings, overrides, sliderPreset)
+ const changed = samplingIsChanged(settings, overrides, sliderPreset) || (customRows?.length ?? 0) > 0
// F1 (review-w2ui.md, 18.09.2026): Reset only deletes THIS chat's own
// override, so it must go by whether one exists, not by whether the
// EFFECTIVE value differs from the shipped default (`changed` above): that
// is also true when only the Settings page moved and this chat never
// touched its own slider, and Reset then has nothing to delete.
- const ownSampling = hasOwnSampling(overrides)
+ const ownSampling = hasOwnSampling(overrides) || (customRows?.length ?? 0) > 0
const write = (patch: SamplingOverrides) => {
if (activeId) setSampling(activeId, patch)
}
@@ -421,6 +429,17 @@ export function SamplingControls() {
<ThinkBudgetRow />
+ <div className="space-y-1 border-t border-gray-700/50 pt-1.5">
+ <div className="text-gray-400">{CUSTOM_PARAMS_LABEL}</div>
+ <CustomParamsEditor
+ rows={customRows ?? []}
+ onChange={(rows) => { if (activeId) setCustomRows(activeId, rows) }}
+ inherited={!isGroupChat(groupModels) && lines[0]?.personaCustom?.length
+ ? { source: lines[0].source.replace(/^Persona /, 'persona '), rows: lines[0].personaCustom }
+ : undefined}
+ />
+ </div>
+
{lines.length > 0 && (
<div data-testid="sampling-speakers" className="space-y-1 border-t border-gray-700/50 pt-1.5">
{lines.map((line) => (
diff --git a/src/components/chat/__tests__/composer-grammar.test.ts b/src/components/chat/__tests__/composer-grammar.test.ts
index 09fbb3d0..9510c67f 100644
--- a/src/components/chat/__tests__/composer-grammar.test.ts
+++ b/src/components/chat/__tests__/composer-grammar.test.ts
@@ -580,7 +580,8 @@ describe('der Zustand kommt aus ARIA, nicht aus einer zweiten Klassenkette', ()
// solange Denken an ist, und das meldet der Think-Knopf daneben.
expect(EFFORT).toMatch(/aria-label=\{`Reasoning effort: \$\{effortText\}`\}/)
expect(EFFORT).not.toContain('aria-pressed')
- expect(INPUT).toContain('<span>{effortText}</span>')
+ // Visible in the button; below 26rem only for the screen reader (P2, 375 px).
+ expect(INPUT).toContain('<span className="@max-[26rem]:sr-only">{effortText}</span>')
// Das blaue Pill der Release-Linie ist weg. Es war dieselbe Farbe wie der
// Fokusring, direkt neben dem Knopf, an dem sie schon abgebaut war.
// Geprueft wird der KNOPF, nicht die Datei: das Blau der Ablegeflaeche
diff --git a/src/components/chat/__tests__/custom-params-in-the-sampling-popup.test.tsx b/src/components/chat/__tests__/custom-params-in-the-sampling-popup.test.tsx
new file mode 100644
index 00000000..d268036a
--- /dev/null
+++ b/src/components/chat/__tests__/custom-params-in-the-sampling-popup.test.tsx
@@ -0,0 +1,58 @@
+// @vitest-environment jsdom
+/**
+ * GH #198: the chat's Sampling popup keeps this chat's own custom rows, shows
+ * which ones come from the persona, and Reset clears the chat's rows too.
+ *
+ * Run: npx vitest run src/components/chat/__tests__/custom-params-in-the-sampling-popup.test.tsx
+ */
+import { beforeEach, afterEach, describe, expect, it } from 'vitest'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { useChatStore } from '../../../stores/chatStore'
+import { useSettingsStore } from '../../../stores/settingsStore'
+import { useModelStore } from '../../../stores/modelStore'
+import { SamplingControls } from '../SamplingControls'
+
+const conversation = {
+ id: 'c1', title: 'c1', messages: [], model: 'm', systemPrompt: '', createdAt: 0, updatedAt: 0,
+ personaId: 'baron', personaEnabled: true,
+}
+const baron = {
+ id: 'baron', name: 'Baron', icon: 'User', systemPrompt: 'You are Baron.', isBuiltIn: false,
+ customParams: [{ key: 'xtc_threshold', type: 'number' as const, value: '0.1' }],
+}
+
+beforeEach(() => {
+ useChatStore.setState({ conversations: [conversation] as never, activeConversationId: 'c1' })
+ useSettingsStore.setState({ personas: [baron] })
+ useSettingsStore.getState().updateSettings({ personasEnabled: true })
+ useModelStore.setState({ activeModel: 'ollama::qwen3:4b' })
+})
+afterEach(cleanup)
+
+const conv = () => useChatStore.getState().conversations.find((c) => c.id === 'c1')!
+
+describe('custom rows in the Sampling popup', () => {
+ it('a row typed here is this chat\'s own, and the persona\'s keys are named', () => {
+ render(<SamplingControls />)
+ fireEvent.click(screen.getByTestId('sampling-trigger'))
+ expect(screen.getByTestId('custom-params-inherited').textContent).toBe('From persona Baron: xtc_threshold')
+ fireEvent.click(screen.getByTestId('custom-param-add'))
+ fireEvent.change(screen.getByLabelText('Parameter name'), { target: { value: 'dry_base' } })
+ fireEvent.change(screen.getByLabelText('Parameter value'), { target: { value: '1.75' } })
+ expect(conv().customParams).toEqual([{ key: 'dry_base', type: 'number', value: '1.75' }])
+ // The speaker line lists both, the chat's and the persona's.
+ const line = screen.getByTestId('sampling-speaker').textContent ?? ''
+ expect(line).toContain('dry_base 1.75')
+ expect(line).toContain('xtc_threshold 0.1')
+ expect(screen.getByTestId('sampling-changed-marker')).toBeTruthy()
+ })
+
+ it('Reset clears the chat\'s rows, the persona keeps its own', () => {
+ useChatStore.getState().setConversationCustomParams('c1', [{ key: 'dry_base', type: 'number', value: '2' }])
+ render(<SamplingControls />)
+ fireEvent.click(screen.getByTestId('sampling-trigger'))
+ fireEvent.click(screen.getByRole('button', { name: 'Reset' }))
+ expect(conv().customParams).toBeUndefined()
+ expect(useSettingsStore.getState().personas[0].customParams).toHaveLength(1)
+ })
+})
diff --git a/src/components/chat/__tests__/enter-key-setting-in-the-chat.test.tsx b/src/components/chat/__tests__/enter-key-setting-in-the-chat.test.tsx
new file mode 100644
index 00000000..69666d8c
--- /dev/null
+++ b/src/components/chat/__tests__/enter-key-setting-in-the-chat.test.tsx
@@ -0,0 +1,99 @@
+// @vitest-environment jsdom
+/**
+ * GH #202: the Enter key setting reaches the composer and the edit field of
+ * an earlier message.
+ *
+ * Run: npx vitest run src/components/chat/__tests__/enter-key-setting-in-the-chat.test.tsx
+ */
+import { describe, it, expect, afterEach, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { ChatInput } from '../ChatInput'
+import { MessageBubble } from '../MessageBubble'
+import { useSettingsStore } from '../../../stores/settingsStore'
+
+afterEach(() => {
+ cleanup()
+ useSettingsStore.getState().updateSettings({ enterKey: 'send' })
+})
+
+function composer(onSend: (text: string) => void) {
+ const view = render(<ChatInput onSend={(text) => onSend(text)} onStop={() => {}} isGenerating={false} modelReady={() => true} />)
+ const field = view.container.querySelector('textarea[data-lu-composer]') as HTMLTextAreaElement
+ fireEvent.change(field, { target: { value: 'line one' } })
+ return field
+}
+
+describe('the composer', () => {
+ it('"Sends": Enter sends, as before', () => {
+ const onSend = vi.fn()
+ const field = composer(onSend)
+ fireEvent.keyDown(field, { key: 'Enter' })
+ expect(onSend).toHaveBeenCalledWith('line one')
+ })
+
+ it('"New line": Enter does not send, Ctrl+Enter does, and the placeholder says so', () => {
+ useSettingsStore.getState().updateSettings({ enterKey: 'newline' })
+ const onSend = vi.fn()
+ const field = composer(onSend)
+ expect(field.placeholder).toMatch(/\+Enter to send/)
+ const plain = fireEvent.keyDown(field, { key: 'Enter' })
+ expect(plain).toBe(true) // not prevented: the browser adds the line
+ expect(onSend).not.toHaveBeenCalled()
+ fireEvent.keyDown(field, { key: 'Enter', ctrlKey: true })
+ expect(onSend).toHaveBeenCalledWith('line one')
+ })
+})
+
+describe('the edit field of an earlier message', () => {
+ const msg = { id: 'u1', role: 'user' as const, content: 'hello', timestamp: 1 }
+
+ function openEdit(onEdit: (id: string, text: string) => boolean) {
+ render(<MessageBubble message={msg} onEdit={onEdit} />)
+ fireEvent.click(screen.getByRole('button', { name: 'Edit message' }))
+ return screen.getByLabelText('Edit message text') as HTMLTextAreaElement
+ }
+
+ it('"Sends": Enter saves and closes, Ctrl+Enter resends', () => {
+ const onEdit = vi.fn(() => true)
+ let field = openEdit(onEdit)
+ fireEvent.keyDown(field, { key: 'Enter' })
+ expect(screen.queryByLabelText('Edit message text')).toBeNull()
+ expect(onEdit).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'Edit message' }))
+ field = screen.getByLabelText('Edit message text') as HTMLTextAreaElement
+ fireEvent.change(field, { target: { value: 'hello again' } })
+ fireEvent.keyDown(field, { key: 'Enter', ctrlKey: true })
+ expect(onEdit).toHaveBeenCalledWith('u1', 'hello again')
+ })
+
+ it('"New line": Enter stays in the field, Ctrl+Enter saves, Ctrl+Shift+Enter resends', () => {
+ useSettingsStore.getState().updateSettings({ enterKey: 'newline' })
+ const onEdit = vi.fn(() => true)
+ let field = openEdit(onEdit)
+ expect(screen.getByTestId('edit-key-hint').textContent).toMatch(/\+Enter saves, Enter adds a line/)
+ fireEvent.keyDown(field, { key: 'Enter' })
+ expect(screen.getByLabelText('Edit message text')).toBeTruthy()
+ fireEvent.keyDown(field, { key: 'Enter', ctrlKey: true })
+ expect(screen.queryByLabelText('Edit message text')).toBeNull()
+ expect(onEdit).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'Edit message' }))
+ field = screen.getByLabelText('Edit message text') as HTMLTextAreaElement
+ fireEvent.change(field, { target: { value: 'again' } })
+ fireEvent.keyDown(field, { key: 'Enter', ctrlKey: true, shiftKey: true })
+ expect(onEdit).toHaveBeenCalledWith('u1', 'again')
+ })
+})
+
+describe('a phone-wide window (375 px)', () => {
+ it('Sampling, the model and Send have their own line below 26rem, not pushed out of the row', () => {
+ render(<ChatInput onSend={() => {}} onStop={() => {}} isGenerating={false} modelReady={() => true} />)
+ const cluster = screen.getByTestId('composer-right-cluster')
+ expect(cluster.className).toMatch(/@max-\[26rem\]:basis-full/)
+ expect(cluster.contains(screen.getByTestId('composer-send-slot'))).toBe(true)
+ const row = cluster.parentElement as HTMLElement
+ expect(row.className).toMatch(/@max-\[26rem\]:flex-wrap/)
+ // The query container is the parent: a container cannot query itself.
+ expect((row.parentElement as HTMLElement).className).toMatch(/@container/)
+ expect(row.className).not.toMatch(/@container/)
+ })
+})
diff --git a/src/components/chat/__tests__/the-code-composer-is-one-quiet-row.test.ts b/src/components/chat/__tests__/the-code-composer-is-one-quiet-row.test.ts
index 6f72fb39..4aafc56e 100644
--- a/src/components/chat/__tests__/the-code-composer-is-one-quiet-row.test.ts
+++ b/src/components/chat/__tests__/the-code-composer-is-one-quiet-row.test.ts
@@ -150,12 +150,19 @@ describe('Stop never opens a second line', () => {
describe('the action bar is one quiet row', () => {
const bar = INPUT.indexOf('flex flex-nowrap items-center gap-1 px-2 py-1.5')
- it('does not wrap, at any width, in any state', () => {
+ it('does not wrap in any state; by width only below 26rem, and then always the same way', () => {
expect(bar).toBeGreaterThan(-1)
- // Only the image-preview strip above the textarea is still allowed to
- // wrap; the action row itself never is.
+ // Only the image-preview strip above the textarea may wrap freely. The
+ // action row may only wrap in a phone-wide composer (P2, LU 3.0.9: at
+ // 375 px Sampling, the model and Send were pushed out of the frame), and
+ // then the right cluster is a full line of its own, so the height depends
+ // on the WIDTH alone and never on a run starting.
const wrappers = [...INPUT.matchAll(/className="([^"]*\bflex-wrap\b[^"]*)"/g)].map((m) => m[1])
- expect(wrappers).toEqual(['flex gap-1.5 mb-1.5 flex-wrap'])
+ expect(wrappers).toEqual([
+ 'flex gap-1.5 mb-1.5 flex-wrap',
+ 'flex flex-nowrap items-center gap-1 px-2 py-1.5 min-h-[38px] border-t border-gray-200 dark:border-white/[0.05] @max-[26rem]:flex-wrap',
+ ])
+ expect(INPUT).toMatch(/className="contents @max-\[26rem\]:flex @max-\[26rem\]:basis-full[^"]*" data-testid="composer-right-cluster"/)
})
it('keeps a fixed row height whether a run is in flight or not', () => {
diff --git a/src/components/models/__tests__/hints-name-real-controls.test.ts b/src/components/models/__tests__/hints-name-real-controls.test.ts
index 140e5a41..a8a238e8 100644
--- a/src/components/models/__tests__/hints-name-real-controls.test.ts
+++ b/src/components/models/__tests__/hints-name-real-controls.test.ts
@@ -177,7 +177,7 @@ describe('the effort control in the composer says what it is and what it costs',
// Showing Max while sending high would be a control that lies, on the one
// axis where the user is paying attention because it costs money.
expect(chatInput).toMatch(/const effortNow = clampEffort\(effortLevels, /)
- expect(chatInput).toMatch(/<span>\{effortText\}<\/span>/)
+ expect(chatInput).toMatch(/<span[^>]*>\{effortText\}<\/span>/)
})
it('it is drawn only where it is true: a declared ladder and thinking really on', () => {
diff --git a/src/components/personas/PersonaPanel.tsx b/src/components/personas/PersonaPanel.tsx
index 4e5024a9..1e26db52 100644
--- a/src/components/personas/PersonaPanel.tsx
+++ b/src/components/personas/PersonaPanel.tsx
@@ -203,6 +203,7 @@ export function PersonaPanel() {
initialSampling={editingPersona.sampling}
initialNote={editingPersona.note}
initialNoteDepth={editingPersona.noteDepth}
+ initialCustomParams={editingPersona.customParams}
onDone={() => setEditingId(null)}
/>
) : showEditor ? (
diff --git a/src/components/personas/SystemPromptEditor.tsx b/src/components/personas/SystemPromptEditor.tsx
index f69af8f9..8c0221bd 100644
--- a/src/components/personas/SystemPromptEditor.tsx
+++ b/src/components/personas/SystemPromptEditor.tsx
@@ -5,6 +5,9 @@ import { useSettingsStore } from '../../stores/settingsStore'
import type { SamplerValues } from '../../types/settings'
import { clampSampling, TEMPERATURE_MAX, TEMPERATURE_HELP, TEMPERATURE_HELP_LABEL } from '../../lib/sampling'
import { HelpMark } from '../ui/HelpMark'
+import { LongTextField } from '../ui/LongTextField'
+import { CustomParamsEditor, CUSTOM_PARAMS_LABEL } from '../chat/CustomParamsEditor'
+import { cleanCustomParams, type CustomParam } from '../../lib/custom-params'
import { HighTemperatureWarning } from '../chat/HighTemperatureWarning'
import { DEFAULT_NOTE_DEPTH, MAX_NOTE_DEPTH, clampNoteDepth } from '../../lib/persona-note'
@@ -50,6 +53,13 @@ export function samplingFromDraft(draft: SamplingDraft): SamplerValues | undefin
return Object.keys(clamped).length > 0 ? clamped : undefined
}
+/** GH #198: the rows to keep on the persona: every row with a name, as
+ * typed. Undefined when none, so the persona carries no empty field. */
+export function customParamsFromDraft(rows: CustomParam[]): CustomParam[] | undefined {
+ const kept = cleanCustomParams(rows).filter((r) => r.key.trim() !== '')
+ return kept.length > 0 ? kept : undefined
+}
+
/** GH #181: the typed reminder as persona fields. Whitespace only is none. */
export function noteFromDraft(text: string, depth: string): { note?: string; noteDepth?: number } {
const note = text.trim()
@@ -69,6 +79,8 @@ interface SystemPromptEditorProps {
/** GH #181: the persona's reminder and its depth, when editing one. */
initialNote?: string
initialNoteDepth?: number
+ /** GH #198: the persona's custom sampling rows, when editing one. */
+ initialCustomParams?: CustomParam[]
/** Called after a successful save/update or a cancel, so the parent can
* close the editor. */
onDone?: () => void
@@ -81,6 +93,7 @@ export function SystemPromptEditor({
initialSampling,
initialNote = '',
initialNoteDepth,
+ initialCustomParams,
onDone,
}: SystemPromptEditorProps) {
const { addPersona, updatePersona } = useSettingsStore()
@@ -90,15 +103,17 @@ export function SystemPromptEditor({
const [note, setNote] = useState(initialNote)
const [tempHelp, setTempHelp] = useState(false)
const [noteDepth, setNoteDepth] = useState(String(initialNoteDepth ?? DEFAULT_NOTE_DEPTH))
+ const [customParams, setCustomParams] = useState<CustomParam[]>(() => initialCustomParams ?? [])
const isEditing = !!editingId
const handleSave = () => {
if (!name.trim() || !prompt.trim()) return
// GH #181: an empty reminder is no reminder, and then no depth either.
const reminder = noteFromDraft(note, noteDepth)
+ const custom = customParamsFromDraft(customParams)
if (isEditing) {
// Only the user-editable fields — keep id/icon/isBuiltIn untouched.
- updatePersona(editingId!, { name: name.trim(), systemPrompt: prompt.trim(), sampling: samplingFromDraft(sampling), note: reminder.note, noteDepth: reminder.noteDepth })
+ updatePersona(editingId!, { name: name.trim(), systemPrompt: prompt.trim(), sampling: samplingFromDraft(sampling), note: reminder.note, noteDepth: reminder.noteDepth, customParams: custom })
} else {
addPersona({
id: uuid(),
@@ -108,12 +123,14 @@ export function SystemPromptEditor({
isBuiltIn: false,
...(samplingFromDraft(sampling) ? { sampling: samplingFromDraft(sampling) } : {}),
...(reminder.note ? reminder : {}),
+ ...(custom ? { customParams: custom } : {}),
})
setName('')
setPrompt('')
setSampling({})
setNote('')
setNoteDepth(String(DEFAULT_NOTE_DEPTH))
+ setCustomParams([])
}
onDone?.()
}
@@ -126,12 +143,16 @@ export function SystemPromptEditor({
placeholder="Persona name..."
className="w-full px-3 py-2 rounded-lg bg-white/5 border border-white/10 text-white placeholder-gray-500 focus:outline-none focus:border-white/20 text-sm"
/>
- <textarea
+ {/* GH #197: drags taller, remembers it, opens large with search. */}
+ <LongTextField
value={prompt}
- onChange={(e) => setPrompt(e.target.value)}
+ onChange={setPrompt}
+ storageKey="persona-prompt"
+ label="System prompt"
placeholder="System prompt..."
rows={4}
- className="w-full px-3 py-2 rounded-lg bg-white/5 border border-white/10 text-white placeholder-gray-500 focus:outline-none focus:border-white/20 text-sm resize-none"
+ testId="persona-prompt"
+ className="block w-full px-3 py-2 rounded-lg bg-white/5 border border-white/10 text-white placeholder-gray-500 focus:outline-none focus:border-white/20 text-sm"
/>
<fieldset data-testid="persona-sampling" className="rounded-lg border border-white/10 px-3 pb-2 pt-1">
<legend className="px-1 text-[0.6rem] text-gray-400">Sampling for this persona</legend>
@@ -178,15 +199,24 @@ export function SystemPromptEditor({
Empty fields follow the chat. A value moved in the chat's Sampling popup still wins. Each value only reaches a backend that reads it.
</p>
</fieldset>
+ <fieldset data-testid="persona-custom-params" className="rounded-lg border border-white/10 px-3 pb-2 pt-1 text-xs text-gray-200">
+ <legend className="px-1 t-micro text-gray-400">{CUSTOM_PARAMS_LABEL}</legend>
+ <CustomParamsEditor rows={customParams} onChange={setCustomParams} testId="persona-custom-param-list" />
+ <p className="mt-1 t-micro text-gray-500">
+ For samplers without a field above, e.g. dry_base, xtc_threshold, logit_bias. A chat's own row with the same name wins.
+ </p>
+ </fieldset>
<fieldset data-testid="persona-note" className="rounded-lg border border-white/10 px-3 pb-2 pt-1">
<legend className="px-1 t-micro text-gray-400">Reminder</legend>
- <textarea
+ <LongTextField
value={note}
- onChange={(e) => setNote(e.target.value)}
- aria-label="Reminder"
+ onChange={setNote}
+ storageKey="persona-reminder"
+ label="Reminder"
placeholder="Short rules to keep in mind, e.g. speech style or status block format..."
rows={2}
- className="w-full px-2 py-1 rounded bg-white/5 border border-white/10 text-white placeholder-gray-600 focus:outline-none focus:border-white/20 text-xs resize-none"
+ testId="persona-reminder"
+ className="block w-full px-2 py-1 rounded bg-white/5 border border-white/10 text-white placeholder-gray-600 focus:outline-none focus:border-white/20 text-xs"
/>
<label className="mt-1.5 flex items-center gap-2 t-micro text-gray-400">
<span>Messages from the end</span>
diff --git a/src/components/personas/__tests__/der-personensatz-verspricht-nichts-falsches.test.tsx b/src/components/personas/__tests__/der-personensatz-verspricht-nichts-falsches.test.tsx
index bcb93c1f..17ec9203 100644
--- a/src/components/personas/__tests__/der-personensatz-verspricht-nichts-falsches.test.tsx
+++ b/src/components/personas/__tests__/der-personensatz-verspricht-nichts-falsches.test.tsx
@@ -47,7 +47,7 @@ describe('der Satz unter dem Personen-Hauptschalter', () => {
// Der Satz zeigt auf ein Menue. Steht dort ein anderer Name, schickt er
// den Kunden ins Leere, also wird der Name gegen die Quelle gehalten.
const quelle = readFileSync(join(__dirname, '../../chat/PluginsDropdown.tsx'), 'utf8')
- expect(quelle).toContain('<span>Plugins</span>')
+ expect(quelle).toContain('>Plugins</span>')
expect(quelle).toContain('aria-label="Plugins"')
expect(quelle).toContain("'Enable persona for this chat'")
expect(SATZ).toContain('Plugins menu')
diff --git a/src/components/settings/MemorySettings.tsx b/src/components/settings/MemorySettings.tsx
index f28340a4..5ca492bc 100644
--- a/src/components/settings/MemorySettings.tsx
+++ b/src/components/settings/MemorySettings.tsx
@@ -8,6 +8,7 @@ import { getProviderIdFromModel } from '../../api/providers/model-name'
import type { ProviderId } from '../../api/providers/types'
import { useChatStore, persistConversationMemoryScope } from '../../stores/chatStore'
import { getModelMaxTokens } from '../../lib/context-compaction'
+import { LongTextField } from '../ui/LongTextField'
// Eine Schreibweise fuer jedes Kontextfenster. Hier stand zweimal
// `Math.round(ctx / 1024)}K`, eine eigene Rechnung: bei 32000 Token sagte
// diese Zeile 31K und der Rest der Oberflaeche 31.3K.
@@ -556,12 +557,14 @@ function MemorySettingsPanel() {
className="w-full px-2 py-1 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 placeholder-gray-600 focus:outline-none focus:border-white/20"
autoFocus
/>
- <textarea
+ <LongTextField
value={newContent}
- onChange={(e) => { setNewContent(e.target.value); if (addError) setAddError(null) }}
+ onChange={(v) => { setNewContent(v); if (addError) setAddError(null) }}
+ storageKey="memory-content"
+ label="Memory details"
placeholder="Details… (required)"
rows={2}
- className="w-full px-2 py-1 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 placeholder-gray-600 focus:outline-none resize-none"
+ className="block w-full px-2 py-1 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 placeholder-gray-600 focus:outline-none"
/>
{addError && (
<p className="text-[0.55rem] text-red-400 px-0.5">{addError}</p>
@@ -613,11 +616,13 @@ function MemorySettingsPanel() {
maxLength={60}
className="w-full px-2 py-0.5 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 focus:outline-none"
/>
- <textarea
+ <LongTextField
value={editContent}
- onChange={(e) => setEditContent(e.target.value)}
+ onChange={setEditContent}
+ storageKey="memory-content"
+ label="Memory details"
rows={2}
- className="w-full px-2 py-0.5 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 focus:outline-none resize-none"
+ className="block w-full px-2 py-0.5 rounded bg-white/5 border border-white/10 text-[0.65rem] text-gray-300 focus:outline-none"
/>
<div className="flex gap-1.5">
<label className="text-xs">Project ID
diff --git a/src/components/settings/SettingsPage.tsx b/src/components/settings/SettingsPage.tsx
index c43ccf5a..5955f710 100644
--- a/src/components/settings/SettingsPage.tsx
+++ b/src/components/settings/SettingsPage.tsx
@@ -18,6 +18,7 @@ import { useUIStore } from '../../stores/uiStore'
import { SliderControl } from './SliderControl'
import { THINK_BUDGET_STEP, normalizeThinkBudget } from '../../lib/think-budget'
import { InlineToggle } from './InlineToggle'
+import { composerHint, enterKeyMode } from '../../lib/enter-key'
import { SpeechSettings } from './SpeechSettings'
import { LogFileSettings } from './LogFileSettings'
import { PersonaPanel } from '../personas/PersonaPanel'
@@ -1984,6 +1985,26 @@ export function SettingsPage() {
enabled={settings.emojiAutoReplace}
onChange={() => updateSettings({ emojiAutoReplace: !settings.emojiAutoReplace })}
/>
+ {/* GH #202: what Enter does in the chat box and in an edit. */}
+ <div className="flex items-center justify-between gap-2" data-testid="enter-key-setting">
+ <span className="t-control text-gray-700 dark:text-gray-400" title="In the chat box and when you edit an earlier message.">Enter key</span>
+ <div className="flex gap-1" role="radiogroup" aria-label="Enter key">
+ {([['send', 'Sends'], ['newline', 'New line']] as const).map(([mode, text]) => (
+ <button
+ key={mode}
+ role="radio"
+ aria-checked={enterKeyMode(settings.enterKey) === mode}
+ onClick={() => updateSettings({ enterKey: mode })}
+ className={`px-2 py-1 rounded t-micro transition-colors ${
+ enterKeyMode(settings.enterKey) === mode ? 'bg-lu-accent-soft ring-1 ring-lu-accent-edge dark:ring-lu-accent text-gray-900 dark:text-white' : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'
+ }`}
+ >
+ {text}
+ </button>
+ ))}
+ </div>
+ </div>
+ <p className="t-micro text-gray-500 -mt-1" data-testid="enter-key-hint">{composerHint(enterKeyMode(settings.enterKey), isMacOS())}{enterKeyMode(settings.enterKey) === 'newline' ? '. In an edit, add Shift to save and resend.' : '.'}</p>
</Section>
<Section title="Generation">
diff --git a/src/components/ui/LongTextField.tsx b/src/components/ui/LongTextField.tsx
new file mode 100644
index 00000000..4db69e89
--- /dev/null
+++ b/src/components/ui/LongTextField.tsx
@@ -0,0 +1,309 @@
+import { useCallback, useDeferredValue, useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react'
+import { ChevronDown, ChevronUp, Maximize2, Search } from 'lucide-react'
+import { Modal } from './Modal'
+import { estimateTokens } from '../../lib/token-estimate'
+import { findMatches, readFieldHeight, writeFieldHeight, formatCount } from '../../lib/long-text'
+
+/**
+ * GH #197: a text area for long texts, the persona prompt, the reminder and a
+ * memory. Prompts of 40,000 tokens are real (the issue), so:
+ *
+ * - the bottom edge drags, and the height a person dragged to is kept per
+ * field (`storageKey`), in this browser only;
+ * - "Expand" opens the same text in a window almost as large as the app,
+ * with search (Ctrl+F, Cmd+F on a Mac) and a character and token count;
+ * - the count and the search run on a deferred copy of the text, so typing
+ * into 160,000 characters never waits for them.
+ *
+ * Both boxes edit the one value the caller holds; nothing is copied or saved
+ * on close.
+ */
+export interface LongTextFieldProps {
+ value: string
+ onChange: (value: string) => void
+ /** Remembers the dragged height under this name. */
+ storageKey: string
+ /** Name of the field, for the screen reader and the window title. */
+ label: string
+ placeholder?: string
+ rows?: number
+ className?: string
+ /** Extra props for the inline text area (data-testid and the like). */
+ testId?: string
+}
+
+/** The text that says how long the field is: "1,234 characters · ~310 tokens". */
+export function lengthLine(text: string, tokens: number): string {
+ return `${formatCount(text.length)} characters · ~${formatCount(tokens)} tokens`
+}
+
+const isFindKey = (e: KeyboardEvent | globalThis.KeyboardEvent) =>
+ (e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === 'f'
+
+export function LongTextField({ value, onChange, storageKey, label, placeholder, rows = 4, className = '', testId }: LongTextFieldProps) {
+ const ref = useRef<HTMLTextAreaElement>(null)
+ const [expanded, setExpanded] = useState(false)
+ const [searchFirst, setSearchFirst] = useState(false)
+
+ // The kept height goes on before the first paint, so the box does not jump.
+ useLayoutEffect(() => {
+ const el = ref.current
+ const saved = readFieldHeight(storageKey)
+ if (el && saved) el.style.height = `${saved}px`
+ }, [storageKey])
+
+ // A drag on the corner changes the height and nothing else does (the width
+ // follows the layout), so every new height seen here is one to keep.
+ useEffect(() => {
+ const el = ref.current
+ if (!el || typeof ResizeObserver === 'undefined') return
+ let last = el.offsetHeight
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const ro = new ResizeObserver(() => {
+ const h = el.offsetHeight
+ if (h === last || h === 0) return
+ last = h
+ clearTimeout(timer)
+ timer = setTimeout(() => writeFieldHeight(storageKey, h), 200)
+ })
+ ro.observe(el)
+ return () => { ro.disconnect(); clearTimeout(timer) }
+ }, [storageKey])
+
+ const open = (withSearch: boolean) => {
+ setSearchFirst(withSearch)
+ setExpanded(true)
+ }
+
+ return (
+ <div className="relative">
+ <textarea
+ ref={ref}
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ onKeyDown={(e) => {
+ if (isFindKey(e)) {
+ e.preventDefault()
+ open(true)
+ }
+ }}
+ aria-label={label}
+ placeholder={placeholder}
+ rows={rows}
+ data-testid={testId}
+ data-long-text={storageKey}
+ className={`${className} resize-y min-h-[3rem] pr-7`}
+ />
+ <button
+ type="button"
+ onClick={() => open(false)}
+ aria-label={`Expand ${label}`}
+ title={`Open ${label} in a large editor with search (Ctrl+F)`}
+ data-testid={testId ? `${testId}-expand` : undefined}
+ className="absolute right-1.5 top-1.5 rounded p-0.5 text-gray-500 hover:text-gray-200 hover:bg-white/10"
+ >
+ <Maximize2 size={11} />
+ </button>
+ {expanded && (
+ <ExpandedEditor
+ value={value}
+ onChange={onChange}
+ label={label}
+ placeholder={placeholder}
+ searchFirst={searchFirst}
+ testId={testId}
+ onClose={() => {
+ setExpanded(false)
+ ref.current?.focus()
+ }}
+ />
+ )}
+ </div>
+ )
+}
+
+function ExpandedEditor({
+ value, onChange, label, placeholder, searchFirst, testId, onClose,
+}: {
+ value: string
+ onChange: (value: string) => void
+ label: string
+ placeholder?: string
+ searchFirst: boolean
+ testId?: string
+ onClose: () => void
+}) {
+ const areaRef = useRef<HTMLTextAreaElement>(null)
+ const searchRef = useRef<HTMLInputElement>(null)
+ const [query, setQuery] = useState('')
+ const [current, setCurrent] = useState(0)
+ // Counting and searching 160,000 characters on every key would make the
+ // typing wait; React runs these on the deferred copy after the key landed.
+ const deferred = useDeferredValue(value)
+ const deferredQuery = useDeferredValue(query)
+ const tokens = useMemo(() => estimateTokens(deferred), [deferred])
+ const matches = useMemo(() => findMatches(deferred, deferredQuery), [deferred, deferredQuery])
+ const shown = matches.length === 0 ? 0 : Math.min(current, matches.length - 1)
+ const hit = query && deferredQuery === query ? matches[shown] : undefined
+ const markLayerRef = useRef<HTMLDivElement>(null)
+ const [scrollbarGap, setScrollbarGap] = useState<number | undefined>(undefined)
+ const syncMarkLayer = useCallback(() => {
+ const area = areaRef.current
+ const layer = markLayerRef.current
+ if (!area || !layer) return
+ layer.scrollTop = area.scrollTop
+ }, [])
+ // The layer follows the text area's scroll and leaves room for its scrollbar.
+ useLayoutEffect(() => {
+ const area = areaRef.current
+ if (!area || !hit) return
+ const pad = parseFloat(getComputedStyle(area).paddingRight) || 0
+ setScrollbarGap(pad + (area.offsetWidth - area.clientWidth))
+ syncMarkLayer()
+ }, [hit, syncMarkLayer])
+
+ useEffect(() => {
+ const target = searchFirst ? searchRef.current : areaRef.current
+ // After the Modal has put its own first focus.
+ const t = setTimeout(() => target?.focus(), 0)
+ return () => clearTimeout(t)
+ }, [searchFirst])
+
+ const reveal = useCallback((index: number) => {
+ const area = areaRef.current
+ const m = matches[index]
+ if (!area || !m) return
+ area.setSelectionRange(m.start, m.end)
+ area.scrollTop = Math.max(0, offsetOf(area, m.start) - area.clientHeight / 3)
+ }, [matches])
+
+ // A new search goes to its first hit.
+ useEffect(() => {
+ setCurrent(0)
+ if (deferredQuery) reveal(0)
+ // Only on a new query, not on every edit of the text.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [deferredQuery])
+
+ const step = (dir: 1 | -1) => {
+ if (matches.length === 0) return
+ const next = (shown + dir + matches.length) % matches.length
+ setCurrent(next)
+ reveal(next)
+ }
+
+ const onKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
+ // Escape closes this editor and nothing under it: the memory panel and
+ // other popovers listen on the document too and would close as well,
+ // dropping what was typed there. React handles this before the document.
+ if (e.key === 'Escape') {
+ e.preventDefault()
+ e.stopPropagation()
+ onClose()
+ return
+ }
+ if (isFindKey(e)) {
+ e.preventDefault()
+ searchRef.current?.focus()
+ searchRef.current?.select()
+ }
+ }
+
+ return (
+ <Modal open onClose={onClose} title={label} maxWidth="max-w-5xl" panelPad="p-4">
+ <div onKeyDown={onKeyDown} className="flex flex-col gap-2" data-testid={testId ? `${testId}-editor` : 'long-text-editor'}>
+ <div className="flex flex-wrap items-center gap-2">
+ <label className="flex min-w-0 flex-1 items-center gap-1.5 rounded-md border border-white/10 bg-white/5 px-2 py-1 focus-within:border-white/30">
+ <Search size={12} className="shrink-0 text-gray-500" />
+ <input
+ ref={searchRef}
+ type="text"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault()
+ step(e.shiftKey ? -1 : 1)
+ }
+ }}
+ placeholder="Find (Ctrl+F)"
+ aria-label="Find in text"
+ data-testid="long-text-find"
+ className="lu-fokus-am-kasten min-w-0 flex-1 bg-transparent text-xs text-gray-200 placeholder-gray-500 focus:outline-none"
+ />
+ <span className="shrink-0 tabular-nums t-micro text-gray-500" data-testid="long-text-find-count">
+ {query ? (matches.length ? `${shown + 1} / ${matches.length}` : 'no match') : ''}
+ </span>
+ </label>
+ <button type="button" aria-label="Previous match" onClick={() => step(-1)} disabled={!matches.length}
+ className="rounded p-1 text-gray-400 hover:bg-white/10 disabled:opacity-40"><ChevronUp size={14} /></button>
+ <button type="button" aria-label="Next match" onClick={() => step(1)} disabled={!matches.length}
+ className="rounded p-1 text-gray-400 hover:bg-white/10 disabled:opacity-40"><ChevronDown size={14} /></button>
+ </div>
+ {/* The current hit is drawn behind the text: a selection in a text
+ area that does not have the focus (the keys are in the search
+ box) is not shown in WebKit. The layer holds only the text up to
+ the hit, in the same font and width, so it lines up with it. */}
+ <div className="relative rounded-lg border border-white/10 bg-white/5 focus-within:border-white/20">
+ {hit && (
+ <div
+ ref={markLayerRef}
+ aria-hidden
+ data-testid="long-text-mark-layer"
+ className="pointer-events-none absolute inset-0 overflow-hidden whitespace-pre-wrap break-words px-3 py-2 font-mono text-xs leading-relaxed text-transparent"
+ style={{ paddingRight: scrollbarGap }}
+ >
+ {value.slice(0, hit.start)}
+ <mark data-testid="long-text-current-hit" className="rounded-sm bg-lu-accent/50 text-transparent">{value.slice(hit.start, hit.end)}</mark>
+ </div>
+ )}
+ <textarea
+ ref={areaRef}
+ value={value}
+ onChange={(e) => onChange(e.target.value)}
+ onScroll={syncMarkLayer}
+ aria-label={label}
+ placeholder={placeholder}
+ spellCheck={false}
+ data-testid="long-text-area"
+ className="lu-fokus-am-kasten relative block h-[70vh] min-h-[12rem] w-full resize-y bg-transparent px-3 py-2 font-mono text-xs leading-relaxed text-gray-100 placeholder-gray-600 focus:outline-none scrollbar-thin"
+ />
+ </div>
+ <div className="flex items-center justify-between gap-2 t-micro text-gray-500">
+ <span data-testid="long-text-count">{lengthLine(deferred, tokens)}</span>
+ <span>Tokens are estimated. Changes apply right away.</span>
+ </div>
+ </div>
+ </Modal>
+ )
+}
+
+/**
+ * How far down in the text area the character at `index` sits, in pixels.
+ * A hidden copy with the same width, font and wrapping holds the text up to
+ * that point; its height is the answer. Only measured on a search step.
+ */
+function offsetOf(area: HTMLTextAreaElement, index: number): number {
+ const cs = getComputedStyle(area)
+ const mirror = document.createElement('div')
+ for (const p of ['fontFamily', 'fontSize', 'fontWeight', 'lineHeight', 'letterSpacing', 'paddingLeft', 'paddingRight', 'paddingTop', 'tabSize'] as const) {
+ mirror.style[p] = cs[p]
+ }
+ // clientWidth is the content plus the padding, without border and scrollbar.
+ mirror.style.boxSizing = 'border-box'
+ mirror.style.position = 'absolute'
+ mirror.style.visibility = 'hidden'
+ mirror.style.left = '-99999px'
+ mirror.style.top = '0'
+ mirror.style.whiteSpace = 'pre-wrap'
+ mirror.style.overflowWrap = 'break-word'
+ mirror.style.width = `${area.clientWidth}px`
+ mirror.textContent = area.value.slice(0, index)
+ const mark = document.createElement('span')
+ mark.textContent = '​'
+ mirror.appendChild(mark)
+ document.body.appendChild(mirror)
+ const top = mark.offsetTop
+ mirror.remove()
+ return top
+}
diff --git a/src/components/ui/__tests__/long-text-field.test.tsx b/src/components/ui/__tests__/long-text-field.test.tsx
new file mode 100644
index 00000000..459943b9
--- /dev/null
+++ b/src/components/ui/__tests__/long-text-field.test.tsx
@@ -0,0 +1,108 @@
+// @vitest-environment jsdom
+/**
+ * GH #197: the persona prompt, the reminder and a memory drag taller and open
+ * in a large editor with search (Ctrl+F) and a character and token count.
+ *
+ * Run: npx vitest run src/components/ui/__tests__/long-text-field.test.tsx
+ */
+import { describe, it, expect, afterEach, beforeEach } from 'vitest'
+import { useState } from 'react'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { LongTextField } from '../LongTextField'
+import { SystemPromptEditor } from '../../personas/SystemPromptEditor'
+import { useSettingsStore } from '../../../stores/settingsStore'
+
+beforeEach(() => localStorage.clear())
+afterEach(cleanup)
+
+function Harness({ initial }: { initial: string }) {
+ const [v, setV] = useState(initial)
+ return <LongTextField value={v} onChange={setV} storageKey="t" label="System prompt" testId="f" />
+}
+
+describe('the long text field', () => {
+ it('drags taller (resize-y) and opens with its kept height', () => {
+ localStorage.setItem('lu-long-text-height:t', '420')
+ render(<Harness initial="x" />)
+ const field = screen.getByTestId('f') as HTMLTextAreaElement
+ expect(field.className).toMatch(/resize-y/)
+ expect(field.className).not.toMatch(/resize-none/)
+ expect(field.style.height).toBe('420px')
+ })
+
+ it('Expand opens the same text large, with a count, and edits go through', async () => {
+ render(<Harness initial={'The baron. '.repeat(10)} />)
+ fireEvent.click(screen.getByRole('button', { name: 'Expand System prompt' }))
+ const area = await screen.findByTestId('long-text-area') as HTMLTextAreaElement
+ expect(area.value).toBe('The baron. '.repeat(10))
+ await waitFor(() => expect(screen.getByTestId('long-text-count').textContent).toMatch(/^110 characters · ~\d+ tokens$/))
+ fireEvent.change(area, { target: { value: 'short' } })
+ expect((screen.getByTestId('f') as HTMLTextAreaElement).value).toBe('short')
+ })
+
+ it('Ctrl+F in the field opens the editor at the search, which counts and steps', async () => {
+ render(<Harness initial="Baron one, baron two, BARON three" />)
+ fireEvent.keyDown(screen.getByTestId('f'), { key: 'f', ctrlKey: true })
+ const find = await screen.findByTestId('long-text-find') as HTMLInputElement
+ await waitFor(() => expect(document.activeElement).toBe(find))
+ fireEvent.change(find, { target: { value: 'baron' } })
+ await waitFor(() => expect(screen.getByTestId('long-text-find-count').textContent).toBe('1 / 3'))
+ fireEvent.keyDown(find, { key: 'Enter' })
+ expect(screen.getByTestId('long-text-find-count').textContent).toBe('2 / 3')
+ const area = screen.getByTestId('long-text-area') as HTMLTextAreaElement
+ expect([area.selectionStart, area.selectionEnd]).toEqual([11, 16])
+ fireEvent.keyDown(find, { key: 'Enter', shiftKey: true })
+ expect(screen.getByTestId('long-text-find-count').textContent).toBe('1 / 3')
+ })
+
+ it('a 40,000 token prompt types without the count or search in the way', () => {
+ const big = 'The baron walks slowly through the hall. '.repeat(4000)
+ render(<Harness initial={big} />)
+ fireEvent.click(screen.getByRole('button', { name: 'Expand System prompt' }))
+ const area = screen.getByTestId('long-text-area') as HTMLTextAreaElement
+ const t0 = performance.now()
+ for (let i = 0; i < 20; i++) act(() => { fireEvent.change(area, { target: { value: big + 'x'.repeat(i) } }) })
+ const perKey = (performance.now() - t0) / 20
+ // jsdom is far slower than a WebView; this only keeps an O(n²) slip out.
+ expect(perKey).toBeLessThan(100)
+ })
+})
+
+describe('Escape', () => {
+ it('closes the editor and nothing under it', async () => {
+ let outer = 0
+ const onDoc = (e: KeyboardEvent) => { if (e.key === 'Escape') outer++ }
+ document.addEventListener('keydown', onDoc)
+ render(<Harness initial="abc" />)
+ fireEvent.click(screen.getByRole('button', { name: 'Expand System prompt' }))
+ const area = await screen.findByTestId('long-text-area')
+ fireEvent.keyDown(area, { key: 'Escape' })
+ await waitFor(() => expect(screen.queryByTestId('long-text-area')).toBeNull())
+ document.removeEventListener('keydown', onDoc)
+ expect(outer).toBe(0)
+ })
+})
+
+describe('where it is used', () => {
+ it('the persona editor has it for the prompt and the reminder, and saves custom rows', () => {
+ const before = useSettingsStore.getState().personas.length
+ render(<SystemPromptEditor />)
+ expect(screen.getByRole('button', { name: 'Expand System prompt' })).toBeTruthy()
+ expect(screen.getByRole('button', { name: 'Expand Reminder' })).toBeTruthy()
+ fireEvent.change(screen.getByPlaceholderText('Persona name...'), { target: { value: 'Baron' } })
+ fireEvent.change(screen.getByPlaceholderText('System prompt...'), { target: { value: 'You are Baron.' } })
+ fireEvent.click(screen.getByTestId('custom-param-add'))
+ fireEvent.change(screen.getByLabelText('Parameter name'), { target: { value: 'dry_base' } })
+ fireEvent.change(screen.getByLabelText('Parameter value'), { target: { value: '1.75' } })
+ fireEvent.click(screen.getByTestId('custom-param-add'))
+ fireEvent.change(screen.getAllByLabelText('Parameter name')[1], { target: { value: 'temperature' } })
+ expect(screen.getByTestId('custom-param-problem').textContent).toMatch(/own field/)
+ fireEvent.click(screen.getByRole('button', { name: 'Save Persona' }))
+ const saved = useSettingsStore.getState().personas
+ expect(saved).toHaveLength(before + 1)
+ expect(saved[saved.length - 1].customParams).toEqual([
+ { key: 'dry_base', type: 'number', value: '1.75' },
+ { key: 'temperature', type: 'number', value: '' },
+ ])
+ })
+})
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 4a57708f..98d9bc12 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -169,7 +169,7 @@ import { asString, errorText, isRecord, prop } from '../types/json-guards'
import type { ToolArgs } from '../api/mcp/types'
import { CREDITS_EXHAUSTED_MESSAGE } from '../lib/credits-exhausted'
import { buildChatSystemPrompt } from '../lib/system-prompt'
-import { withChatPersona, samplingPresetFor, speakerPersonaFor } from '../lib/chat-persona'
+import { withChatPersona, samplingPresetFor, speakerCustomParams, speakerPersonaFor } from '../lib/chat-persona'
import { injectPersonaNote, noteTokens, personaNoteOf } from '../lib/persona-note'
// ── Hook ──────────────────────────────────────────────────────
@@ -1763,10 +1763,17 @@ export function useAgentChat() {
// GH #175: the chat persona's preset sits under this chat's own values,
// while the persona is on for the chat, as its prompt is.
const { personas: allPersonas, activePersonaId: pickedPersonaId } = useSettingsStore.getState()
- const personaPreset = samplingConv
- ? samplingPresetFor(samplingConv, activeModel, allPersonas, pickedPersonaId, settings.personasEnabled !== false).preset
+ const speaker = samplingConv
+ ? samplingPresetFor(samplingConv, activeModel, allPersonas, pickedPersonaId, settings.personasEnabled !== false)
: undefined
- const sampling = { topK: settings.topK, ...buildSamplingRequest(settings, convSampling, personaPreset) }
+ const personaPreset = speaker?.preset
+ // GH #198: the custom rows go along here too, the chat's over the persona's.
+ const customParams = samplingConv ? speakerCustomParams(samplingConv, speaker?.persona) : {}
+ const sampling = {
+ topK: settings.topK,
+ ...buildSamplingRequest(settings, convSampling, personaPreset),
+ ...(Object.keys(customParams).length > 0 ? { customParams } : {}),
+ }
// Small-Model Mode (Knob 6): gently clamp temperature for tool turns.
// FOLKLORE, not measured — research found NO temperature finding for
// tool-calling. A low, low-entropy setting is *plausible* for valid
diff --git a/src/lib/__tests__/custom-sampling-params.test.ts b/src/lib/__tests__/custom-sampling-params.test.ts
new file mode 100644
index 00000000..05531847
--- /dev/null
+++ b/src/lib/__tests__/custom-sampling-params.test.ts
@@ -0,0 +1,119 @@
+/**
+ * GH #198: custom sampling parameters as rows of key, type and value, on a
+ * persona and on a chat. The chat's row wins over the persona's by key, a
+ * key LU sets with its own field is never taken from a row, and in a group
+ * every member brings its own persona's rows.
+ *
+ * Run: npx vitest run src/lib/__tests__/custom-sampling-params.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import {
+ cleanCustomParams, customParamProblem, mergeCustomParams, parseCustomParam, resolveCustomParams,
+ type CustomParam,
+} from '../custom-params'
+import { speakerSamplingOptions } from '../chat-persona'
+import { speakerSamplingLines } from '../speaker-sampling-lines'
+import type { Persona } from '../../types/settings'
+
+const row = (key: string, type: CustomParam['type'], value: string): CustomParam => ({ key, type, value })
+
+/** The examples of the issue, typed as a person would. */
+const ISSUE: CustomParam[] = [
+ row('dry_base', 'number', '1.75'),
+ row('dry_allowed_length', 'number', '4'),
+ row('dry_penalty_last_n', 'number', '-1'),
+ row('dry_sequence_breakers', 'json', '["\\n", ":", "\\"", "*"]'),
+ row('xtc_threshold', 'number', '0.1'),
+ row('xtc_probability', 'number', '0.5'),
+ row('banned_strings', 'json', '["ministrations", "shivers down"]'),
+ row('logit_bias', 'json', '{"128": -100}'),
+]
+
+describe('one row', () => {
+ it('parses by type', () => {
+ expect(parseCustomParam(row('a', 'number', ' 1.75 '))).toEqual({ ok: true, value: 1.75 })
+ expect(parseCustomParam(row('a', 'boolean', 'false'))).toEqual({ ok: true, value: false })
+ expect(parseCustomParam(row('a', 'string', ' keep spaces '))).toEqual({ ok: true, value: ' keep spaces ' })
+ expect(parseCustomParam(row('a', 'json', '{"128": -100}'))).toEqual({ ok: true, value: { '128': -100 } })
+ })
+
+ it('says why a row cannot go', () => {
+ expect(customParamProblem(row('', 'number', '1'))).toMatch(/name/)
+ expect(customParamProblem(row('a b', 'number', '1'))).toMatch(/Letters/)
+ expect(customParamProblem(row('x', 'number', 'abc'))).toMatch(/number/)
+ expect(customParamProblem(row('x', 'boolean', 'yes'))).toMatch(/true or false/)
+ expect(customParamProblem(row('x', 'json', '[1,'))).toMatch(/JSON/)
+ for (const fixed of ['temperature', 'top_p', 'max_tokens', 'min_p', 'num_ctx', 'num_predict', 'messages', 'model', 'stream']) {
+ expect(customParamProblem(row(fixed, 'number', '1')), fixed).toMatch(/own field/)
+ }
+ for (const r of ISSUE) expect(customParamProblem(r), r.key).toBeUndefined()
+ })
+})
+
+describe('the rows in force', () => {
+ it('every example of the issue goes out with its typed value', () => {
+ expect(resolveCustomParams(ISSUE)).toEqual({
+ dry_base: 1.75,
+ dry_allowed_length: 4,
+ dry_penalty_last_n: -1,
+ dry_sequence_breakers: ['\n', ':', '"', '*'],
+ xtc_threshold: 0.1,
+ xtc_probability: 0.5,
+ banned_strings: ['ministrations', 'shivers down'],
+ logit_bias: { '128': -100 },
+ })
+ })
+
+ it('the chat row wins over the persona row with the same key; the rest of both stays', () => {
+ const merged = mergeCustomParams([row('dry_base', 'number', '2')], [row('dry_base', 'number', '1.75'), row('xtc_threshold', 'number', '0.1')])
+ expect(resolveCustomParams(merged)).toEqual({ dry_base: 2, xtc_threshold: 0.1 })
+ })
+
+ it('a broken or fixed row is left out, the others go', () => {
+ expect(resolveCustomParams([row('temperature', 'number', '2'), row('x', 'json', '{'), row('ok', 'number', '1')])).toEqual({ ok: 1 })
+ })
+
+ it('a stored list is cleaned: wrong shapes dropped, at most 32 rows', () => {
+ const many = Array.from({ length: 40 }, (_, i) => row(`k${i}`, 'number', '1'))
+ expect(cleanCustomParams([...many, { key: 1 }, null])).toHaveLength(32)
+ expect(cleanCustomParams([{ key: 'a', type: 'float', value: '1' }])).toEqual([])
+ expect(cleanCustomParams('nope')).toEqual([])
+ })
+})
+
+const P = (id: string, name: string, customParams?: CustomParam[]): Persona => ({
+ id, name, icon: 'User', systemPrompt: `You are ${name}.`, isBuiltIn: false, ...(customParams ? { customParams } : {}),
+})
+const SETTINGS = { temperature: 0.7, topP: 0.9, maxTokens: 0, topK: 40, personasEnabled: true }
+
+describe('per speaker (chat > persona > nothing)', () => {
+ const baron = P('baron', 'Baron', [row('dry_base', 'number', '1.75'), row('xtc_threshold', 'number', '0.1')])
+ const walt = P('walt', 'Walt', [row('logit_bias', 'json', '{"128": -100}')])
+
+ it('a plain chat with the persona on gets its rows, the chat row on top', () => {
+ const conv = { personaId: 'baron', personaEnabled: true, customParams: [row('dry_base', 'number', '2')] }
+ const opts = speakerSamplingOptions(SETTINGS, conv, 'ollama::m', [baron], undefined, true)
+ expect(opts.customParams).toEqual({ dry_base: 2, xtc_threshold: 0.1 })
+ })
+
+ it('a persona switched off for the chat brings no rows; the chat\'s own still go', () => {
+ const conv = { personaId: 'baron', personaEnabled: false, customParams: [row('foo', 'string', 'bar')] }
+ expect(speakerSamplingOptions(SETTINGS, conv, 'ollama::m', [baron], undefined, true).customParams).toEqual({ foo: 'bar' })
+ expect(speakerSamplingOptions(SETTINGS, { personaId: 'baron', personaEnabled: false }, 'ollama::m', [baron], undefined, true).customParams).toBeUndefined()
+ })
+
+ it('in a group each member brings its own persona\'s rows', () => {
+ const conv = { groupModels: ['ollama::a', 'ollama::b'], groupPersonas: { 'ollama::a': 'baron', 'ollama::b': 'walt' } }
+ expect(speakerSamplingOptions(SETTINGS, conv, 'ollama::a', [baron, walt], undefined, true).customParams).toEqual({ dry_base: 1.75, xtc_threshold: 0.1 })
+ expect(speakerSamplingOptions(SETTINGS, conv, 'ollama::b', [baron, walt], undefined, true).customParams).toEqual({ logit_bias: { '128': -100 } })
+ })
+
+ it('the popup lines list the rows each member runs on, and mark them not sent on LU Cloud', () => {
+ const conv = { groupModels: ['ollama::a', 'lu-cloud::c'], groupPersonas: { 'ollama::a': 'baron', 'lu-cloud::c': 'walt' } }
+ const lines = speakerSamplingLines({ settings: SETTINGS, conv, activeModel: null, personas: [baron, walt], activePersonaId: undefined, providers: {} })
+ const a = lines.find((l) => l.model === 'ollama::a')!
+ const c = lines.find((l) => l.model === 'lu-cloud::c')!
+ expect(a.values).toContainEqual({ label: 'dry_base', text: '1.75', sent: true })
+ expect(c.values).toContainEqual({ label: 'logit_bias', text: '{"128": -100}', sent: false })
+ })
+})
diff --git a/src/lib/__tests__/enter-key-setting.test.ts b/src/lib/__tests__/enter-key-setting.test.ts
new file mode 100644
index 00000000..c652298a
--- /dev/null
+++ b/src/lib/__tests__/enter-key-setting.test.ts
@@ -0,0 +1,67 @@
+/**
+ * GH #202: a setting for the Enter key. "Sends" keeps what Enter always did;
+ * "New line" makes Enter a line break and Ctrl+Enter (Cmd+Enter on a Mac)
+ * sends, or saves an edit, with Shift as well saving and resending.
+ *
+ * Run: npx vitest run src/lib/__tests__/enter-key-setting.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { composerHint, composerPlaceholder, composerSends, editKeyAction, editShortcuts, enterKeyMode, type KeyLike } from '../enter-key'
+import { DEFAULT_SETTINGS } from '../constants'
+
+const key = (over: Partial<KeyLike> = {}): KeyLike => ({ key: 'Enter', shiftKey: false, ctrlKey: false, metaKey: false, ...over })
+
+describe('the composer', () => {
+ it('"Sends" (the default): Enter sends, Shift+Enter is a line', () => {
+ expect(enterKeyMode(DEFAULT_SETTINGS.enterKey)).toBe('send')
+ expect(composerSends(key(), 'send')).toBe(true)
+ expect(composerSends(key({ ctrlKey: true }), 'send')).toBe(true)
+ expect(composerSends(key({ shiftKey: true }), 'send')).toBe(false)
+ })
+
+ it('"New line": Enter is a line, Ctrl+Enter or Cmd+Enter sends', () => {
+ expect(composerSends(key(), 'newline')).toBe(false)
+ expect(composerSends(key({ shiftKey: true }), 'newline')).toBe(false)
+ expect(composerSends(key({ ctrlKey: true }), 'newline')).toBe(true)
+ expect(composerSends(key({ metaKey: true }), 'newline')).toBe(true)
+ })
+
+ it('a key the input method is still composing never sends', () => {
+ expect(composerSends(key({ isComposing: true }), 'send')).toBe(false)
+ expect(composerSends(key({ ctrlKey: true, isComposing: true }), 'newline')).toBe(false)
+ })
+
+ it('other keys never send', () => {
+ expect(composerSends(key({ key: 'a' }), 'send')).toBe(false)
+ })
+
+ it('an unknown stored value is the default', () => {
+ expect(enterKeyMode(undefined)).toBe('send')
+ expect(enterKeyMode('weird')).toBe('send')
+ expect(enterKeyMode('newline')).toBe('newline')
+ })
+
+ it('the hint names the shortcut, Cmd on a Mac', () => {
+ expect(composerHint('send', true)).toBe('Enter sends, Shift+Enter adds a line')
+ expect(composerHint('newline', true)).toBe('Cmd+Enter sends, Enter adds a line')
+ expect(composerHint('newline', false)).toBe('Ctrl+Enter sends, Enter adds a line')
+ expect(composerPlaceholder('send', false)).toBe('Message...')
+ expect(composerPlaceholder('newline', false)).toBe('Message... (Ctrl+Enter to send)')
+ })
+})
+
+describe('the edit field of an earlier message', () => {
+ it('"Sends": Enter saves, Ctrl+Enter resends, Shift+Enter is a line', () => {
+ expect(editKeyAction(key(), 'send')).toBe('save')
+ expect(editKeyAction(key({ ctrlKey: true }), 'send')).toBe('resend')
+ expect(editKeyAction(key({ shiftKey: true }), 'send')).toBe('none')
+ })
+
+ it('"New line": Enter is a line, Ctrl+Enter saves, Ctrl+Shift+Enter resends', () => {
+ expect(editKeyAction(key(), 'newline')).toBe('none')
+ expect(editKeyAction(key({ shiftKey: true }), 'newline')).toBe('none')
+ expect(editKeyAction(key({ metaKey: true }), 'newline')).toBe('save')
+ expect(editKeyAction(key({ ctrlKey: true, shiftKey: true }), 'newline')).toBe('resend')
+ expect(editShortcuts('newline', true)).toEqual({ save: 'Cmd+Enter', resend: 'Cmd+Shift+Enter', hint: 'Cmd+Enter saves, Enter adds a line' })
+ })
+})
diff --git a/src/lib/__tests__/long-text-field.test.ts b/src/lib/__tests__/long-text-field.test.ts
new file mode 100644
index 00000000..87f0232f
--- /dev/null
+++ b/src/lib/__tests__/long-text-field.test.ts
@@ -0,0 +1,51 @@
+/**
+ * GH #197: the pure parts of the long text field: search, the count, and the
+ * kept height.
+ *
+ * Run: npx vitest run src/lib/__tests__/long-text-field.test.ts
+ */
+// @vitest-environment jsdom
+import { describe, it, expect, beforeEach } from 'vitest'
+import { findMatches, formatCount, readFieldHeight, writeFieldHeight, MAX_MATCHES } from '../long-text'
+
+beforeEach(() => localStorage.clear())
+
+describe('search', () => {
+ it('finds every place, ignoring case', () => {
+ expect(findMatches('Baron and the baron', 'BARON')).toEqual([{ start: 0, end: 5 }, { start: 14, end: 19 }])
+ expect(findMatches('abc', '')).toEqual([])
+ expect(findMatches('abc', 'x')).toEqual([])
+ })
+
+ it('stops counting at a cap, so one letter in a huge prompt stays cheap', () => {
+ expect(findMatches('a'.repeat(20_000), 'a')).toHaveLength(MAX_MATCHES)
+ })
+
+ it('a 40,000 token prompt (160,000 characters) is searched in well under a frame', () => {
+ const text = 'The baron walks slowly through the hall. '.repeat(4000)
+ const t0 = performance.now()
+ const hits = findMatches(text, 'hall')
+ expect(hits).toHaveLength(4000)
+ expect(performance.now() - t0).toBeLessThan(50)
+ })
+})
+
+describe('count', () => {
+ it('groups thousands the same way everywhere', () => {
+ expect(formatCount(160000)).toBe('160,000')
+ expect(formatCount(999)).toBe('999')
+ })
+})
+
+describe('the kept height', () => {
+ it('remembers per field and ignores nonsense', () => {
+ expect(readFieldHeight('persona-prompt')).toBeUndefined()
+ writeFieldHeight('persona-prompt', 412.4)
+ expect(readFieldHeight('persona-prompt')).toBe(412)
+ expect(readFieldHeight('persona-reminder')).toBeUndefined()
+ writeFieldHeight('persona-prompt', 5)
+ expect(readFieldHeight('persona-prompt')).toBe(412)
+ localStorage.setItem('lu-long-text-height:x', 'abc')
+ expect(readFieldHeight('x')).toBeUndefined()
+ })
+})
diff --git a/src/lib/chat-persona.ts b/src/lib/chat-persona.ts
index a50bd6ec..41709df9 100644
--- a/src/lib/chat-persona.ts
+++ b/src/lib/chat-persona.ts
@@ -2,6 +2,7 @@ import type { Persona, SamplerValues, Settings } from '../types/settings'
import { buildSamplingRequest, type SamplingOverrides, type SamplingRequest } from './sampling'
import { substituteMacros, DEFAULT_USER_NAME } from './character-card'
import { isGroupChat } from './group-chat'
+import { mergeCustomParams, resolveCustomParams, type CustomParam } from './custom-params'
/**
* Which persona a chat speaks as, and which prompt that means (GH #170).
@@ -153,12 +154,29 @@ export function samplingPresetFor(
*/
export function speakerSamplingOptions(
settings: Pick<Settings, 'temperature' | 'topP' | 'maxTokens' | 'topK'>,
- conv: Parameters<typeof samplingPresetFor>[0] & { sampling?: SamplingOverrides },
+ conv: Parameters<typeof samplingPresetFor>[0] & { sampling?: SamplingOverrides; customParams?: CustomParam[] },
model: string,
personas: readonly Persona[],
activePersonaId: string | undefined,
personasOn: boolean,
-): SamplingRequest & { topK: number } {
- const { preset } = samplingPresetFor(conv, model, personas, activePersonaId, personasOn)
- return { topK: settings.topK, ...buildSamplingRequest(settings, conv.sampling, preset) }
+): SamplingRequest & { topK: number; customParams?: Record<string, unknown> } {
+ const { persona, preset } = samplingPresetFor(conv, model, personas, activePersonaId, personasOn)
+ const custom = speakerCustomParams(conv, persona)
+ return {
+ topK: settings.topK,
+ ...buildSamplingRequest(settings, conv.sampling, preset),
+ ...(Object.keys(custom).length > 0 ? { customParams: custom } : {}),
+ }
+}
+
+/**
+ * GH #198: the custom sampling rows for one speaker, parsed: this chat's rows
+ * over the rows of the speaker's persona (the one `samplingPresetFor` found,
+ * so a group member brings its own), by key.
+ */
+export function speakerCustomParams(
+ conv: { customParams?: CustomParam[] },
+ persona: Pick<Persona, 'customParams'> | undefined,
+): Record<string, unknown> {
+ return resolveCustomParams(mergeCustomParams(conv.customParams, persona?.customParams))
}
diff --git a/src/lib/constants.ts b/src/lib/constants.ts
index 74ef92bc..f0796e27 100644
--- a/src/lib/constants.ts
+++ b/src/lib/constants.ts
@@ -28,6 +28,8 @@ export const DEFAULT_SETTINGS: Settings = {
thinkingEnabled: true,
// Emoticons to emojis in the chat composer (3.0.7), as chat apps do.
emojiAutoReplace: true,
+ // GH #202: Enter sends, as it always did, until the user picks "new line".
+ enterKey: 'send',
// REA plugin (3.0.7): a local MCP server, off until the user turns it on.
reaPluginEnabled: false,
// Reasoning effort (2.6.8). 'high' is not a taste, it is the rung this
diff --git a/src/lib/custom-params.ts b/src/lib/custom-params.ts
new file mode 100644
index 00000000..8fbccbe4
--- /dev/null
+++ b/src/lib/custom-params.ts
@@ -0,0 +1,156 @@
+/**
+ * GH #198: sampling parameters LU has no field for, as a free list of rows
+ * (key, type, value), on a persona and on a chat.
+ *
+ * Every new sampler of KoboldCpp or llama.cpp (dry_base, xtc_threshold,
+ * banned strings, logit_bias ...) would otherwise need its own field in LU.
+ * A row goes to the backend as typed:
+ *
+ * - OpenAI compatible servers: a top level field of the request body.
+ * - Ollama: a key of `options`.
+ * - Anthropic and the hosted endpoint (LU Cloud): nothing, both refuse
+ * fields they do not know.
+ *
+ * Order, highest first, by key: the chat's row, the speaker's persona row.
+ * Nothing else: without a row the backend keeps its own default. In a group
+ * chat each member brings its own persona's rows; the chat's rows hold for
+ * every member, as the chat's sliders do (lib/chat-persona.ts).
+ *
+ * A key LU already sends from one of its own fields (temperature, top_p,
+ * max_tokens, the persona's samplers ...) or that carries the request itself
+ * (model, messages, stream ...) is never taken from a row: the field stays
+ * the one place for it, and nothing goes out twice. The editor says so on the
+ * row.
+ */
+
+export type CustomParamType = 'string' | 'number' | 'boolean' | 'json'
+
+export const CUSTOM_PARAM_TYPES: readonly CustomParamType[] = ['string', 'number', 'boolean', 'json']
+
+export interface CustomParam {
+ key: string
+ type: CustomParamType
+ /** As typed. Parsed by type when the request is built. */
+ value: string
+}
+
+/** Most rows one persona or one chat keeps. */
+export const MAX_CUSTOM_PARAMS = 32
+/** Longest value kept, enough for a long banned-strings list. */
+export const MAX_CUSTOM_VALUE = 20_000
+
+/** Top level fields of an OpenAI compatible body that LU writes itself. */
+export const OPENAI_FIXED_FIELDS: ReadonlySet<string> = new Set([
+ 'model', 'messages', 'stream', 'stream_options', 'tools', 'tool_choice',
+ 'temperature', 'top_p', 'top_k', 'max_tokens', 'max_completion_tokens',
+ 'min_p', 'repeat_penalty', 'repetition_penalty', 'presence_penalty', 'frequency_penalty', 'dry_multiplier',
+ 'reasoning_effort', 'chat_template_kwargs', 'thinking_budget_tokens', 'continue_final_message',
+ 'response_format', 'n',
+])
+
+/** Keys of Ollama's `options` that LU writes itself. `num_ctx` is the window,
+ * which LU picks so the model is not loaded again by every request. */
+export const OLLAMA_FIXED_OPTIONS: ReadonlySet<string> = new Set([
+ 'temperature', 'top_p', 'top_k', 'num_predict', 'num_ctx',
+ 'min_p', 'repeat_penalty', 'presence_penalty', 'frequency_penalty',
+])
+
+const KEY_PATTERN = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/
+
+export type ParsedParam = { ok: true; value: unknown } | { ok: false; error: string }
+
+/** A row's value as the backend gets it, or why it cannot go. */
+export function parseCustomParam(row: Pick<CustomParam, 'type' | 'value'>): ParsedParam {
+ const text = row.value.trim()
+ switch (row.type) {
+ case 'string':
+ return { ok: true, value: row.value }
+ case 'number': {
+ if (text === '') return { ok: false, error: 'Enter a number.' }
+ const n = Number(text)
+ return Number.isFinite(n) ? { ok: true, value: n } : { ok: false, error: 'Not a number.' }
+ }
+ case 'boolean':
+ if (text === 'true') return { ok: true, value: true }
+ if (text === 'false') return { ok: true, value: false }
+ return { ok: false, error: 'true or false.' }
+ case 'json':
+ if (text === '') return { ok: false, error: 'Enter JSON, e.g. ["\\n", ":"] or {"128": -100}.' }
+ try {
+ return { ok: true, value: JSON.parse(text) }
+ } catch {
+ return { ok: false, error: 'Not valid JSON.' }
+ }
+ }
+}
+
+/** Why this row is not sent, for the editor. Undefined when it is sent
+ * (where the backend takes custom rows at all). */
+export function customParamProblem(row: CustomParam): string | undefined {
+ const key = row.key.trim()
+ if (!key) return 'Give it a name.'
+ if (!KEY_PATTERN.test(key)) return 'Letters, digits, _ . - only.'
+ if (OPENAI_FIXED_FIELDS.has(key) || OLLAMA_FIXED_OPTIONS.has(key)) return 'LU sets this one with its own field.'
+ const parsed = parseCustomParam(row)
+ return parsed.ok ? undefined : parsed.error
+}
+
+/** Rows as kept: well formed, at most MAX_CUSTOM_PARAMS, values capped. A
+ * half-typed row (no key yet) is kept, the editor shows it; only sending
+ * skips it. */
+export function cleanCustomParams(rows: unknown): CustomParam[] {
+ if (!Array.isArray(rows)) return []
+ const out: CustomParam[] = []
+ for (const r of rows) {
+ if (!r || typeof r !== 'object') continue
+ const { key, type, value } = r as Record<string, unknown>
+ if (typeof key !== 'string' || typeof value !== 'string') continue
+ if (!CUSTOM_PARAM_TYPES.includes(type as CustomParamType)) continue
+ out.push({ key: key.slice(0, 64), type: type as CustomParamType, value: value.slice(0, MAX_CUSTOM_VALUE) })
+ if (out.length >= MAX_CUSTOM_PARAMS) break
+ }
+ return out
+}
+
+/** The rows in force for one speaker: the chat's over the persona's, by key. */
+export function mergeCustomParams(chat?: readonly CustomParam[], persona?: readonly CustomParam[]): CustomParam[] {
+ const byKey = new Map<string, CustomParam>()
+ for (const row of persona ?? []) byKey.set(row.key.trim(), row)
+ for (const row of chat ?? []) byKey.set(row.key.trim(), row)
+ return [...byKey.values()]
+}
+
+/** The rows that can go out, parsed: key → value. */
+export function resolveCustomParams(rows: readonly CustomParam[]): Record<string, unknown> {
+ const out: Record<string, unknown> = {}
+ for (const row of rows) {
+ if (customParamProblem(row)) continue
+ const parsed = parseCustomParam(row)
+ if (parsed.ok) out[row.key.trim()] = parsed.value
+ }
+ return out
+}
+
+/** The values as top level fields of an OpenAI compatible body. */
+export function openAiCustomFields(values: Record<string, unknown> | undefined): Record<string, unknown> {
+ const out: Record<string, unknown> = {}
+ for (const [key, value] of Object.entries(values ?? {})) {
+ if (!OPENAI_FIXED_FIELDS.has(key)) out[key] = value
+ }
+ return out
+}
+
+/** The values as keys of Ollama's `options`. */
+export function ollamaCustomOptions(values: Record<string, unknown> | undefined): Record<string, unknown> {
+ const out: Record<string, unknown> = {}
+ for (const [key, value] of Object.entries(values ?? {})) {
+ if (!OLLAMA_FIXED_OPTIONS.has(key)) out[key] = value
+ }
+ return out
+}
+
+/** A row's value in one short line, for the popup's speaker lines. */
+export function customParamText(row: CustomParam): string {
+ const v = row.value.trim()
+ return v.length > 24 ? `${v.slice(0, 23)}…` : v
+}
diff --git a/src/lib/enter-key.ts b/src/lib/enter-key.ts
new file mode 100644
index 00000000..0a54f073
--- /dev/null
+++ b/src/lib/enter-key.ts
@@ -0,0 +1,77 @@
+/**
+ * GH #202: what the Enter key does in the chat composer and in the edit field
+ * of an earlier message.
+ *
+ * - 'send' (the default, as always): Enter sends, or saves an edit; Shift with
+ * Enter is a new line. In an edit Ctrl or Cmd with Enter saves and resends.
+ * - 'newline': Enter is a new line. Ctrl+Enter (Cmd+Enter on a Mac) sends,
+ * or saves an edit; with Shift as well it saves and resends.
+ *
+ * A key pressed while an input method is still composing (Japanese, Chinese,
+ * Korean) belongs to the input method and does nothing here.
+ */
+export type EnterKeyMode = 'send' | 'newline'
+
+export const DEFAULT_ENTER_KEY: EnterKeyMode = 'send'
+
+export interface KeyLike {
+ key: string
+ shiftKey: boolean
+ ctrlKey: boolean
+ metaKey: boolean
+ altKey?: boolean
+ isComposing?: boolean
+}
+
+/** A stored value as a mode; anything else is the default. */
+export function enterKeyMode(value: unknown): EnterKeyMode {
+ return value === 'newline' ? 'newline' : DEFAULT_ENTER_KEY
+}
+
+const isEnter = (e: KeyLike) => e.key === 'Enter' && !e.isComposing && !e.altKey
+const withMod = (e: KeyLike) => e.ctrlKey || e.metaKey
+
+/** Whether this key sends the composer's message. */
+export function composerSends(e: KeyLike, mode: EnterKeyMode): boolean {
+ if (!isEnter(e) || e.shiftKey) return false
+ return mode === 'send' ? true : withMod(e)
+}
+
+/** What this key does in the edit field of an earlier message. */
+export function editKeyAction(e: KeyLike, mode: EnterKeyMode): 'save' | 'resend' | 'none' {
+ if (!isEnter(e)) return 'none'
+ if (mode === 'send') {
+ if (e.shiftKey) return 'none'
+ return withMod(e) ? 'resend' : 'save'
+ }
+ if (!withMod(e)) return 'none'
+ return e.shiftKey ? 'resend' : 'save'
+}
+
+const modName = (mac: boolean) => (mac ? 'Cmd' : 'Ctrl')
+
+/** The composer's hint: how to send and how to break a line. */
+export function composerHint(mode: EnterKeyMode, mac: boolean): string {
+ return mode === 'send'
+ ? 'Enter sends, Shift+Enter adds a line'
+ : `${modName(mac)}+Enter sends, Enter adds a line`
+}
+
+/** The same, short enough for the composer's placeholder in a narrow window. */
+export function composerShortHint(mode: EnterKeyMode, mac: boolean): string {
+ return mode === 'send' ? 'Enter to send' : `${modName(mac)}+Enter to send`
+}
+
+/** The composer's placeholder. In the default mode it stays the plain
+ * "Message..." everyone knows; in "new line" mode it says how to send. */
+export function composerPlaceholder(mode: EnterKeyMode, mac: boolean): string {
+ return mode === 'send' ? 'Message...' : `Message... (${composerShortHint(mode, mac)})`
+}
+
+/** The shortcuts of the edit field's two buttons, for their titles. */
+export function editShortcuts(mode: EnterKeyMode, mac: boolean): { save: string; resend: string; hint: string } {
+ const m = modName(mac)
+ return mode === 'send'
+ ? { save: 'Enter', resend: `${m}+Enter`, hint: 'Enter saves, Shift+Enter adds a line' }
+ : { save: `${m}+Enter`, resend: `${m}+Shift+Enter`, hint: `${m}+Enter saves, Enter adds a line` }
+}
diff --git a/src/lib/long-text.ts b/src/lib/long-text.ts
new file mode 100644
index 00000000..13472942
--- /dev/null
+++ b/src/lib/long-text.ts
@@ -0,0 +1,56 @@
+/**
+ * GH #197: the pure parts of the long text field (components/ui/LongTextField).
+ */
+
+export interface TextMatch {
+ start: number
+ end: number
+}
+
+/** Most hits a search counts. A one-letter search in a 40,000 token prompt
+ * would otherwise build tens of thousands of entries per key. */
+export const MAX_MATCHES = 5000
+
+/** Every place `query` occurs in `text`, ignoring case, in order. */
+export function findMatches(text: string, query: string): TextMatch[] {
+ if (!query) return []
+ const hay = text.toLowerCase()
+ const needle = query.toLowerCase()
+ const out: TextMatch[] = []
+ let at = hay.indexOf(needle)
+ while (at !== -1 && out.length < MAX_MATCHES) {
+ out.push({ start: at, end: at + needle.length })
+ at = hay.indexOf(needle, at + needle.length)
+ }
+ return out
+}
+
+/** 12345 → "12,345", the same in every locale so tests and screens agree. */
+export function formatCount(n: number): string {
+ return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
+}
+
+const PREFIX = 'lu-long-text-height:'
+/** A height outside this range is a broken entry, not a choice. */
+const MIN_HEIGHT = 40
+const MAX_HEIGHT = 4000
+
+/** The height a person dragged this field to, in px, or undefined. */
+export function readFieldHeight(key: string): number | undefined {
+ try {
+ const raw = localStorage.getItem(PREFIX + key)
+ const n = raw === null ? NaN : Number(raw)
+ return Number.isFinite(n) && n >= MIN_HEIGHT && n <= MAX_HEIGHT ? Math.round(n) : undefined
+ } catch {
+ return undefined
+ }
+}
+
+export function writeFieldHeight(key: string, height: number): void {
+ if (!Number.isFinite(height) || height < MIN_HEIGHT || height > MAX_HEIGHT) return
+ try {
+ localStorage.setItem(PREFIX + key, String(Math.round(height)))
+ } catch {
+ // Private window or full storage: the field just opens at its default.
+ }
+}
diff --git a/src/lib/settings-catalog.ts b/src/lib/settings-catalog.ts
index f0f33ccd..4ab07aae 100644
--- a/src/lib/settings-catalog.ts
+++ b/src/lib/settings-catalog.ts
@@ -201,6 +201,7 @@ export const CATALOG: readonly CatalogEntry[] = [
// Look and feel
e('theme', 'Theme', 'general', 'Light or dark app theme.', oneOf(['light', 'dark'])),
e('emojiAutoReplace', 'Emoji replacement', 'general', 'Turn :) into an emoji while typing.', bool()),
+ e('enterKey', 'Enter key', 'general', 'Enter sends the message, or adds a new line (then Ctrl/Cmd+Enter sends).', oneOf(['send', 'newline'])),
e('backgroundMediaTools', 'Keep chatting while it renders', 'general', 'A long picture or video from the chat goes on in the background.', bool()),
e('cloudTeasersEnabled', 'Cloud features in Local mode', 'general', 'Show LU Cloud hints in Local mode.', bool()),
e('cavemanMode', 'Caveman mode', 'general', 'Shorter, terser answers.', oneOf(['off', 'lite', 'full', 'ultra'])),
diff --git a/src/lib/speaker-sampling-lines.ts b/src/lib/speaker-sampling-lines.ts
index 3c36ed2a..e5a020fb 100644
--- a/src/lib/speaker-sampling-lines.ts
+++ b/src/lib/speaker-sampling-lines.ts
@@ -5,6 +5,7 @@ import { extraSamplersFor, type ExtraSamplerKey, type SamplerTarget } from '../a
import { effectiveExtraSamplers, effectiveSampling, type SamplingOverrides } from './sampling'
import { samplingPresetFor } from './chat-persona'
import { isGroupChat, groupSpeakers } from './group-chat'
+import { customParamProblem, customParamText, mergeCustomParams, type CustomParam } from './custom-params'
/**
* GH #175: what the Sampling popup says about each speaker of the open chat.
@@ -21,6 +22,8 @@ export interface SpeakerSamplingLine {
/** "Persona Baron" or "Chat settings". */
source: string
preset?: SamplerValues
+ /** GH #198: the persona's custom rows, for the popup's "From persona" line. */
+ personaCustom?: CustomParam[]
values: { label: string; text: string; sent: boolean }[]
}
@@ -36,7 +39,7 @@ const num = (n: number) => String(Number(n.toFixed(4)))
export function speakerSamplingLines(input: {
settings: Pick<Settings, 'temperature' | 'topP' | 'maxTokens' | 'topK' | 'personasEnabled'>
- conv: Parameters<typeof samplingPresetFor>[0] & { sampling?: SamplingOverrides }
+ conv: Parameters<typeof samplingPresetFor>[0] & { sampling?: SamplingOverrides; customParams?: CustomParam[] }
activeModel: string | null
personas: readonly Persona[]
activePersonaId: string | undefined
@@ -68,11 +71,19 @@ export function speakerSamplingLines(input: {
const v = extras[key]
if (v !== undefined) values.push({ label: EXTRA_LABELS[key], text: num(v), sent: known.includes(key) })
}
+ // GH #198: the custom rows in force, the chat's over the persona's. Only
+ // the ones that go out at all are listed; Anthropic and LU Cloud get none.
+ const customSent = providerId !== 'anthropic' && providerId !== 'lu-cloud'
+ for (const row of mergeCustomParams(conv.customParams, persona?.customParams)) {
+ if (customParamProblem(row)) continue
+ values.push({ label: row.key.trim(), text: customParamText(row), sent: customSent })
+ }
return {
model,
label: names?.[model]?.name && names[model].name !== model ? `${names[model].name} (${displayModelName(model)})` : displayModelName(model),
source: persona ? `Persona ${persona.name}` : 'Chat settings',
preset,
+ personaCustom: persona?.customParams,
values,
}
})
diff --git a/src/stores/chatStore.ts b/src/stores/chatStore.ts
index 14581915..20a34c2c 100644
--- a/src/stores/chatStore.ts
+++ b/src/stores/chatStore.ts
@@ -4,6 +4,7 @@ import { v4 as uuid } from 'uuid'
import type { Conversation, Message, MessageError, ChatArtifact, CompactionRecord, RequestUsage } from '../types/chat'
import type { AgentBlock } from '../types/agent-mode'
import { clampSampling, storedTemperature, type SamplingOverrides } from '../lib/sampling'
+import { cleanCustomParams, type CustomParam } from '../lib/custom-params'
import { idbStorage } from '../lib/idbStorage'
import { externalizeConversations, hasInlineImages } from '../lib/chat-attachments'
import { FILE_ONLY_TEXT } from '../lib/chat-files'
@@ -249,6 +250,9 @@ interface ChatState {
* so it goes back to following the Settings page instead of pinning
* today's defaults into the conversation forever. */
resetConversationSampling: (id: string) => void
+ /** GH #198: replace this chat's custom sampling rows. An empty list
+ * deletes the field, so the chat follows its persona's rows again. */
+ setConversationCustomParams: (id: string, rows: CustomParam[]) => void
/** Group chat v1: the models that answer in turn (capped at 4). */
setGroupModels: (id: string, models: string[]) => void
/** Group chat: the persona ONE participant speaks as in this chat, or
@@ -666,12 +670,25 @@ export const useChatStore = create<ChatState>()(
),
})),
+ setConversationCustomParams: (id, rows) =>
+ set((state) => ({
+ conversations: state.conversations.map((c) => {
+ if (c.id !== id) return c
+ const clean = cleanCustomParams(rows)
+ const next: Conversation = { ...c, customParams: clean, updatedAt: Date.now() }
+ if (clean.length === 0) delete next.customParams
+ return next
+ }),
+ })),
+
resetConversationSampling: (id) =>
set((state) => ({
conversations: state.conversations.map((c) => {
if (c.id !== id) return c
const next = { ...c, updatedAt: Date.now() }
delete next.sampling
+ // GH #198: the chat's custom rows are its own values too.
+ delete next.customParams
return next
}),
})),
diff --git a/src/types/chat.ts b/src/types/chat.ts
index 480e70fb..32eb9101 100644
--- a/src/types/chat.ts
+++ b/src/types/chat.ts
@@ -1,3 +1,4 @@
+import type { CustomParam } from '../lib/custom-params'
import type { AgentBlock } from './agent-mode'
import type { SamplingOverrides } from '../lib/sampling'
@@ -305,6 +306,10 @@ export interface Conversation {
* defaults into it, so a reset chat keeps following the Settings page even
* if its sliders move again afterwards. */
sampling?: SamplingOverrides
+ /** GH #198: this chat's own custom sampling parameters. They win over the
+ * speaker's persona rows with the same key; in a group they hold for every
+ * member. Absent on every chat from before. */
+ customParams?: CustomParam[]
/**
* Kept versions (GH #172, #174), keyed by the id of the message they follow,
* or FORK_ROOT (lib/chat-forks.ts) for a change of the very first message.
diff --git a/src/types/settings.ts b/src/types/settings.ts
index 866d28ce..2e180257 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -1,3 +1,5 @@
+import type { EnterKeyMode } from '../lib/enter-key'
+import type { CustomParam } from '../lib/custom-params'
import type { AgentWorkspace } from './agent-workspace'
import type { EffortLevel } from '../lib/effort'
@@ -90,6 +92,9 @@ export interface Settings {
/** Emoticons such as :) become emojis while typing in the chat composer
* (Chat, Agent, Code; not Create). Default on (lib/emoticons.ts). */
emojiAutoReplace: boolean
+ /** GH #202: what Enter does in the composer and in the edit field of an
+ * earlier message, 'send' (the default) or 'newline' (lib/enter-key.ts). */
+ enterKey?: EnterKeyMode
/** REA, the reverse engineering plugin of the agents (lib/plugins/rea.ts):
* on starts its local MCP server. Default off. */
reaPluginEnabled: boolean
@@ -507,6 +512,10 @@ export interface Persona {
* persona speaks (its chat, or its seat in a group); a chat's own values
* from the Sampling popup still win. Absent on every persona from before. */
sampling?: SamplerValues
+ /** GH #198: sampling parameters LU has no field for, sent as typed where
+ * the backend takes them (lib/custom-params.ts). A chat's own row with the
+ * same key wins. Absent on every persona from before. */
+ customParams?: CustomParam[]
/** GH #181: a short reminder sent near the end of the prompt on every turn
* this persona speaks (lib/persona-note.ts). Payload only, never stored
* in a chat. Absent on every persona from before. */