fix: update settings and skills handling with assistant redirect (#220)

* fix: enable swipe-back suspension on more drawer and remove unused variable

* refactor(frontend): improve dialog component and settings navigation

* fix: disable route swipe suspension in MoreDrawer to prevent unintended navigation

* fix(frontend): enable swipe-back suspension on more drawer route

* refactor(frontend): improve mobile navigation drawer and tab bar

* feat: add schedules service and workspace hook with navigation updates

* chore: add workspace hook, schedules library, and tests

* fix: prevent MoreDrawer sentinel from undoing navigation

* feat: per-agent model selection and UI refinements (#217)

* feat: per-agent model selection and UI refinements

- Add agentModels store with setAgentModel/getAgentModel
- PromptInput uses session model priority and stores agent model on change
- useContextUsage derives model from assistant message instead of global
- Migrate sub-agent/subtask badges from purple to blue with refined styling
- Fix MoreDrawer sentinel to skip history-back on navigation

* refactor: improve per-agent model selection and task tool call status indicators

* feat: add repo management skill and internal repos API

* fix: improve assistant session launcher and UI components

* fix: update atomic-json test assertions

* refactor: split Assistant Mode instructions between AGENTS.md and assistant.md

* loop: todo-header-mobile completed after 3 iterations (#218)

* loop: stt-perf-1 completed after 5 iterations

* fix: load audio worklet per recording context

* fix: canonicalize assistant navigation routes

* fix: adjust scroll-up threshold for header visibility

* fix: update settings and skills handling with assistant redirect

* refactor: simplify context usage indicator and extract token sum helper

* feat: add currently selected model row to popover and fix responsive truncate
This commit is contained in:
Chris Scott authored and GitHub committed 2026-05-07 18:36:03 -04:00
1 parent c7291518c8
commit 74cdeb3926
73 files changed
+4073 -632

No files matched your search

+152
View File
@@ -0,0 +1,152 @@
import { describe, it, expect } from 'vitest'
import { AudioRecorder, downsampleAndConvert, encodeWavFromInt16 } from './audioRecorder'
describe('downsampleAndConvert', () => {
it('should produce correct output length for 48kHz to 16kHz', () => {
const inputLength = 4800
const input = new Float32Array(inputLength)
const output = downsampleAndConvert(input, 48000, 16000)
const expectedLength = Math.floor(inputLength * 16000 / 48000)
expect(output.length).toBe(expectedLength)
expect(output.length).toBe(inputLength / 3)
})
it('should produce correct output length for 44.1kHz to 16kHz', () => {
const inputLength = 4410
const input = new Float32Array(inputLength)
const output = downsampleAndConvert(input, 44100, 16000)
const expectedLength = Math.floor(inputLength * 16000 / 44100)
expect(output.length).toBeCloseTo(expectedLength, 0)
})
it('should clamp values in range [-1, 1] to Int16 range', () => {
const input = new Float32Array([1.0, -1.0, 0.5, -0.5, 0.0])
const output = downsampleAndConvert(input, 16000, 16000)
expect(output[0]).toBe(32767)
expect(output[1]).toBe(-32768)
expect(output[2]).toBeCloseTo(16383, 0)
expect(output[3]).toBeCloseTo(-16384, 0)
expect(output[4]).toBe(0)
})
it('should clamp values outside [-1, 1] range', () => {
const input = new Float32Array([1.5, -1.5, 2.0, -2.0])
const output = downsampleAndConvert(input, 16000, 16000)
expect(output[0]).toBe(32767)
expect(output[1]).toBe(-32768)
expect(output[2]).toBe(32767)
expect(output[3]).toBe(-32768)
})
it('should return Int16Array type', () => {
const input = new Float32Array(100)
const output = downsampleAndConvert(input, 48000, 16000)
expect(output instanceof Int16Array).toBe(true)
})
})
describe('encodeWavFromInt16', () => {
it('should create a Blob with audio/wav type', () => {
const samples = new Int16Array(1000)
const blob = encodeWavFromInt16(samples, 16000, 1)
expect(blob.type).toBe('audio/wav')
})
it('should have RIFF header at offset 0', async () => {
const samples = new Int16Array(1000)
const blob = encodeWavFromInt16(samples, 16000, 1)
const arrayBuffer = await blob.arrayBuffer()
const view = new DataView(arrayBuffer)
const riff = String.fromCharCode(
view.getUint8(0),
view.getUint8(1),
view.getUint8(2),
view.getUint8(3)
)
expect(riff).toBe('RIFF')
})
it('should have WAVE identifier at offset 8', async () => {
const samples = new Int16Array(1000)
const blob = encodeWavFromInt16(samples, 16000, 1)
const arrayBuffer = await blob.arrayBuffer()
const view = new DataView(arrayBuffer)
const wave = String.fromCharCode(
view.getUint8(8),
view.getUint8(9),
view.getUint8(10),
view.getUint8(11)
)
expect(wave).toBe('WAVE')
})
it('should have sample rate at offset 24', async () => {
const samples = new Int16Array(1000)
const blob = encodeWavFromInt16(samples, 16000, 1)
const arrayBuffer = await blob.arrayBuffer()
const view = new DataView(arrayBuffer)
const sampleRate = view.getUint32(24, true)
expect(sampleRate).toBe(16000)
})
it('should have data identifier at offset 36', async () => {
const samples = new Int16Array(1000)
const blob = encodeWavFromInt16(samples, 16000, 1)
const arrayBuffer = await blob.arrayBuffer()
const view = new DataView(arrayBuffer)
const data = String.fromCharCode(
view.getUint8(36),
view.getUint8(37),
view.getUint8(38),
view.getUint8(39)
)
expect(data).toBe('data')
})
it('should have correct file size for 1000 samples', async () => {
const samples = new Int16Array(1000)
const blob = encodeWavFromInt16(samples, 16000, 1)
const arrayBuffer = await blob.arrayBuffer()
expect(arrayBuffer.byteLength).toBe(44 + 1000 * 2)
})
it('should handle different sample rates', async () => {
const samples = new Int16Array(1000)
const blob = encodeWavFromInt16(samples, 44100, 1)
const arrayBuffer = await blob.arrayBuffer()
const view = new DataView(arrayBuffer)
const sampleRate = view.getUint32(24, true)
expect(sampleRate).toBe(44100)
})
it('should handle stereo channels', async () => {
const samples = new Int16Array(1000)
const blob = encodeWavFromInt16(samples, 16000, 2)
const arrayBuffer = await blob.arrayBuffer()
const view = new DataView(arrayBuffer)
const channels = view.getUint16(22, true)
expect(channels).toBe(2)
})
})
describe('AudioRecorder.isSupported', () => {
it('should return boolean without throwing', () => {
expect(() => {
const result = AudioRecorder.isSupported()
expect(typeof result).toBe('boolean')
}).not.toThrow()
})
})
+65 -89
View File
@@ -10,54 +10,68 @@ const DEFAULT_OPTIONS: AudioRecorderOptions = {
channelCount: 1,
}
function encodeWAV(audioBuffer: AudioBuffer): Blob {
const numberOfChannels = audioBuffer.numberOfChannels
const sampleRate = audioBuffer.sampleRate
const format = 1
const bitDepth = 16
const workletModulePromises = new WeakMap<AudioContext, Promise<void>>()
const channelData: Float32Array[] = []
function ensureWorkletLoaded(ctx: AudioContext): Promise<void> {
const existingPromise = workletModulePromises.get(ctx)
for (let i = 0; i < numberOfChannels; i++) {
channelData.push(audioBuffer.getChannelData(i))
if (existingPromise) {
return existingPromise
}
const interleaved = interleave(channelData)
const dataLength = interleaved.length * (bitDepth / 8)
const buffer = new ArrayBuffer(44 + dataLength)
const view = new DataView(buffer)
const promise = ctx.audioWorklet.addModule('/audio-worklet-processor.js')
workletModulePromises.set(ctx, promise)
return promise
}
export function downsampleAndConvert(input: Float32Array, inputRate: number, targetRate: number): Int16Array {
const ratio = inputRate / targetRate
const outputLength = Math.floor(input.length / ratio)
const output = new Int16Array(outputLength)
for (let i = 0; i < outputLength; i++) {
const index = i * ratio
const prevIndex = Math.floor(index)
const nextIndex = prevIndex + 1
const t = index - prevIndex
let sample: number
if (nextIndex >= input.length) {
sample = input[prevIndex]
} else {
sample = input[prevIndex] * (1 - t) + input[nextIndex] * t
}
const clamped = Math.max(-1, Math.min(1, sample))
output[i] = clamped < 0 ? clamped * 32768 : clamped * 32767
}
return output
}
export function encodeWavFromInt16(samples: Int16Array, sampleRate: number, channels: number): Blob {
const dataLength = samples.length * 2
const bufferSize = 44 + dataLength
const buffer = new ArrayBuffer(bufferSize)
const view = new DataView(buffer)
writeString(view, 0, 'RIFF')
view.setUint32(4, 36 + dataLength, true)
writeString(view, 8, 'WAVE')
writeString(view, 12, 'fmt ')
view.setUint32(16, 16, true)
view.setUint16(20, format, true)
view.setUint16(22, numberOfChannels, true)
view.setUint16(20, 1, true)
view.setUint16(22, channels, true)
view.setUint32(24, sampleRate, true)
view.setUint32(28, sampleRate * numberOfChannels * (bitDepth / 8), true)
view.setUint16(32, numberOfChannels * (bitDepth / 8), true)
view.setUint16(34, bitDepth, true)
view.setUint32(28, sampleRate * channels * 2, true)
view.setUint16(32, channels * 2, true)
view.setUint16(34, 16, true)
writeString(view, 36, 'data')
view.setUint32(40, dataLength, true)
floatTo16BitPCM(view, 44, interleaved)
return new Blob([view], { type: 'audio/wav' })
}
function interleave(channelData: Float32Array[]): Float32Array {
const length = channelData[0].length * channelData.length
const result = new Float32Array(length)
let offset = 0
for (let i = 0; i < channelData[0].length; i++) {
for (let channel = 0; channel < channelData.length; channel++) {
result[offset++] = channelData[channel][i]
}
}
return result
new Int16Array(buffer, 44).set(samples)
return new Blob([buffer], { type: 'audio/wav' })
}
function writeString(view: DataView, offset: number, string: string): void {
@@ -66,20 +80,13 @@ function writeString(view: DataView, offset: number, string: string): void {
}
}
function floatTo16BitPCM(view: DataView, offset: number, input: Float32Array): void {
for (let i = 0; i < input.length; i++, offset += 2) {
const s = Math.max(-1, Math.min(1, input[i]))
view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true)
}
}
export class AudioRecorder {
private audioContext: AudioContext | null = null
private mediaStream: MediaStream | null = null
private source: MediaStreamAudioSourceNode | null = null
private processor: ScriptProcessorNode | null = null
private workletNode: AudioWorkletNode | null = null
private chunks: Float32Array[] = []
private chunks: Int16Array[] = []
private totalSamples: number = 0
private state: AudioRecorderState = 'idle'
private options: AudioRecorderOptions
@@ -152,29 +159,32 @@ export class AudioRecorder {
if (this.audioContext.audioWorklet) {
try {
await this.audioContext.audioWorklet.addModule('/audio-worklet-processor.js')
this.workletNode = new AudioWorkletNode(this.audioContext, 'recorder-processor')
this.workletNode.port.onmessage = (e: MessageEvent<Float32Array>) => {
await ensureWorkletLoaded(this.audioContext)
this.workletNode = new AudioWorkletNode(this.audioContext, 'recorder-processor', {
processorOptions: { targetSampleRate: this.options.sampleRate },
})
this.workletNode.port.onmessage = (e: MessageEvent<Int16Array>) => {
this.chunks.push(e.data)
this.totalSamples += e.data.length
}
this.source.connect(this.workletNode)
this.workletNode.connect(this.audioContext.destination)
} catch {
} catch (error) {
this.audioContext.close()
this.audioContext = null
throw new Error('Failed to load audio worklet processor')
throw new Error('Failed to load audio worklet processor', { cause: error })
}
} else if (this.audioContext) {
const bufferSize = 4096
this.processor = this.audioContext.createScriptProcessor(bufferSize, 1, 1)
const targetRate = this.options.sampleRate ?? 16000
const inputRate = this.audioContext.sampleRate
this.processor.onaudioprocess = (e) => {
const inputData = new Float32Array(e.inputBuffer.getChannelData(0))
this.chunks.push(inputData)
this.totalSamples += inputData.length
const inputData = e.inputBuffer.getChannelData(0)
const int16Chunk = downsampleAndConvert(inputData, inputRate, targetRate)
this.chunks.push(int16Chunk)
this.totalSamples += int16Chunk.length
}
this.source.connect(this.processor)
this.processor.connect(this.audioContext.destination)
}
this.setState('recording')
@@ -220,21 +230,13 @@ export class AudioRecorder {
}
try {
const merged = new Float32Array(this.totalSamples)
const merged = new Int16Array(this.totalSamples)
let offset = 0
for (const chunk of this.chunks) {
merged.set(chunk, offset)
offset += chunk.length
}
const audioBuffer = this.audioContext!.createBuffer(
1,
this.totalSamples,
this.audioContext!.sampleRate
)
audioBuffer.copyToChannel(merged, 0)
const wavBlob = encodeWAV(audioBuffer)
const wavBlob = encodeWavFromInt16(merged, this.options.sampleRate ?? 16000, 1)
this.onDataAvailable?.(wavBlob)
} catch {
this.onError?.('Failed to process recording')
@@ -276,30 +278,4 @@ export class AudioRecorder {
this.chunks = []
this.totalSamples = 0
}
getRecordingBlob(): Blob | null {
if (!this.audioContext || this.chunks.length === 0 || this.totalSamples === 0) {
return null
}
try {
const merged = new Float32Array(this.totalSamples)
let offset = 0
for (const chunk of this.chunks) {
merged.set(chunk, offset)
offset += chunk.length
}
const audioBuffer = this.audioContext.createBuffer(
1,
this.totalSamples,
this.audioContext.sampleRate
)
audioBuffer.copyToChannel(merged, 0)
return encodeWAV(audioBuffer)
} catch {
return null
}
}
}
+57 -11
View File
@@ -1,5 +1,39 @@
import { describe, it, expect } from 'vitest';
import { getSessionListPath, getSwipeBackTarget } from './navigation';
import { getSessionListPath, getSwipeBackTarget, getAssistantPath, getAssistantSessionListPath, isAssistantPath } from './navigation';
describe('getAssistantPath', () => {
it('returns /assistant', () => {
expect(getAssistantPath()).toBe('/assistant');
});
});
describe('getAssistantSessionListPath', () => {
it('returns /assistant?view=sessions', () => {
expect(getAssistantSessionListPath()).toBe('/assistant?view=sessions');
});
});
describe('isAssistantPath', () => {
it('returns true for /assistant', () => {
expect(isAssistantPath('/assistant')).toBe(true);
});
it('returns true for legacy /repos/0/assistant', () => {
expect(isAssistantPath('/repos/0/assistant')).toBe(true);
});
it('returns true for legacy /repos/5/assistant', () => {
expect(isAssistantPath('/repos/5/assistant')).toBe(true);
});
it('returns false for /repos/5', () => {
expect(isAssistantPath('/repos/5')).toBe(false);
});
it('returns false for /schedules', () => {
expect(isAssistantPath('/schedules')).toBe(false);
});
});
describe('getSessionListPath', () => {
it('returns repo path for non-assistant sessions', () => {
@@ -7,9 +41,9 @@ describe('getSessionListPath', () => {
expect(getSessionListPath('123', false)).toBe('/repos/123');
});
it('returns assistant path with view=sessions for assistant sessions', () => {
expect(getSessionListPath(42, true)).toBe('/repos/42/assistant?view=sessions');
expect(getSessionListPath('123', true)).toBe('/repos/123/assistant?view=sessions');
it('returns assistant session list path for assistant sessions', () => {
expect(getSessionListPath(42, true)).toBe('/assistant?view=sessions');
expect(getSessionListPath('123', true)).toBe('/assistant?view=sessions');
});
});
@@ -20,12 +54,12 @@ describe('getSwipeBackTarget', () => {
expect(getSwipeBackTarget('/repos/123/sessions/xyz-789', '')).toBe('/repos/123');
});
it('returns assistant path for assistant session detail with assistant=1', () => {
it('returns assistant session list path for assistant session detail with assistant=1', () => {
expect(getSwipeBackTarget('/repos/42/sessions/abc', '?assistant=1')).toBe(
'/repos/42/assistant?view=sessions'
'/assistant?view=sessions'
);
expect(getSwipeBackTarget('/repos/123/sessions/xyz', '?assistant=1')).toBe(
'/repos/123/assistant?view=sessions'
'/assistant?view=sessions'
);
});
@@ -36,12 +70,20 @@ describe('getSwipeBackTarget', () => {
});
describe('assistant route', () => {
it('returns assistant sessions path for assistant route', () => {
expect(getSwipeBackTarget('/repos/123/assistant', '')).toBe('/repos/123/assistant?view=sessions');
it('returns assistant session list path for canonical assistant route', () => {
expect(getSwipeBackTarget('/assistant', '')).toBe('/assistant?view=sessions');
});
it('returns repo path for assistant session list route', () => {
expect(getSwipeBackTarget('/repos/42/assistant', '?view=sessions')).toBe('/repos/42');
it('returns root for assistant session list route', () => {
expect(getSwipeBackTarget('/assistant', '?view=sessions')).toBe('/');
});
it('returns assistant session list path for legacy assistant route', () => {
expect(getSwipeBackTarget('/repos/123/assistant', '')).toBe('/assistant?view=sessions');
});
it('returns root for legacy assistant session list route', () => {
expect(getSwipeBackTarget('/repos/42/assistant', '?view=sessions')).toBe('/');
});
});
@@ -53,6 +95,10 @@ describe('getSwipeBackTarget', () => {
});
describe('schedules routes', () => {
it('returns /assistant for assistant schedules', () => {
expect(getSwipeBackTarget('/repos/0/schedules', '')).toBe('/assistant');
});
it('returns repo path for repo schedules', () => {
expect(getSwipeBackTarget('/repos/42/schedules', '')).toBe('/repos/42');
});
+20 -7
View File
@@ -1,9 +1,20 @@
export function getAssistantPath(): string {
return '/assistant';
}
export function getAssistantSessionListPath(): string {
return '/assistant?view=sessions';
}
export function isAssistantPath(pathname: string): boolean {
return pathname === '/assistant' || /^\/repos\/[^/]+\/assistant$/.test(pathname);
}
export function getSessionListPath(repoId: string | number, isAssistantSession: boolean): string {
const id = String(repoId);
if (isAssistantSession) {
return `/repos/${id}/assistant?view=sessions`;
return getAssistantSessionListPath();
}
return `/repos/${id}`;
return `/repos/${String(repoId)}`;
}
export function getSwipeBackTarget(pathname: string, search = ''): string | null {
@@ -17,13 +28,12 @@ export function getSwipeBackTarget(pathname: string, search = ''): string | null
return getSessionListPath(repoId, isAssistant);
}
if (pathname === '/repos/:id/assistant' || /^\/repos\/[^/]+\/assistant$/.test(pathname)) {
const repoId = pathname.split('/')[2];
if (isAssistantPath(pathname)) {
const params = new URLSearchParams(search);
if (params.get('view') !== 'sessions') {
return getSessionListPath(repoId, true);
return getAssistantSessionListPath();
}
return `/repos/${repoId}`;
return '/';
}
if (/^\/repos\/[^/]+$/.test(pathname)) {
@@ -32,6 +42,9 @@ export function getSwipeBackTarget(pathname: string, search = ''): string | null
if (/^\/repos\/[^/]+\/schedules$/.test(pathname)) {
const repoId = pathname.split('/')[2];
if (repoId === '0') {
return getAssistantPath();
}
return `/repos/${repoId}`;
}
@@ -0,0 +1,73 @@
import { describe, it, expect } from 'vitest'
import {
isAssistantRepoId,
workspaceFromRepo,
workspaceFromAssistant,
} from './workspace'
import type { AssistantModeStatus } from '@opencode-manager/shared/types'
describe('isAssistantRepoId', () => {
it('returns true for repoId 0', () => {
expect(isAssistantRepoId(0)).toBe(true)
})
it('returns false for positive repoId', () => {
expect(isAssistantRepoId(5)).toBe(false)
})
it('returns false for undefined', () => {
expect(isAssistantRepoId(undefined)).toBe(false)
})
})
describe('workspaceFromRepo', () => {
it('returns correct workspace for a repo', () => {
const repo = {
id: 5,
repoUrl: 'https://x/y',
localPath: 'y',
fullPath: '/abs/y',
sourcePath: undefined,
defaultBranch: 'main',
cloneStatus: 'ready' as const,
clonedAt: 0,
}
const workspace = workspaceFromRepo(repo)
expect(workspace).toEqual({
repoId: 5,
kind: 'repo',
name: 'y',
subtitle: 'y',
fullPath: '/abs/y',
backHref: '/repos/5',
})
})
})
describe('workspaceFromAssistant', () => {
it('returns correct workspace for assistant', () => {
const status: AssistantModeStatus = {
repoId: 0,
directory: '/abs/assistant',
relativePath: 'repos/assistant',
files: {
agentsMd: { path: '', exists: false, created: false },
opencodeJson: { path: '', exists: false, created: false },
},
schedulesSkill: { path: '', exists: false, created: false },
}
const workspace = workspaceFromAssistant(status)
expect(workspace).toEqual({
repoId: 0,
kind: 'assistant',
name: 'Assistant',
subtitle: 'Assistant Workspace',
fullPath: '/abs/assistant',
backHref: '/assistant',
})
})
})
+41
View File
@@ -0,0 +1,41 @@
import type { Repo } from '@/api/types'
import type { AssistantModeStatus } from '@opencode-manager/shared/types'
import { getRepoDisplayName } from '@/lib/utils'
import { getAssistantPath } from '@/lib/navigation'
export interface Workspace {
repoId: number
kind: 'assistant' | 'repo'
name: string
subtitle: string
fullPath: string
backHref: string
}
export const ASSISTANT_REPO_ID = 0
export function isAssistantRepoId(repoId: number | undefined): boolean {
return repoId === ASSISTANT_REPO_ID
}
export function workspaceFromRepo(repo: Repo): Workspace {
return {
repoId: repo.id,
kind: 'repo',
name: getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath),
subtitle: repo.localPath,
fullPath: repo.fullPath,
backHref: `/repos/${repo.id}`,
}
}
export function workspaceFromAssistant(status: AssistantModeStatus): Workspace {
return {
repoId: ASSISTANT_REPO_ID,
kind: 'assistant',
name: 'Assistant',
subtitle: 'Assistant Workspace',
fullPath: status.directory,
backHref: getAssistantPath(),
}
}