mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
refactor: remove custom title generation and optimize session updates (#187)
* chore: bump version to 0.9.16 * Remove custom session title generation and rely on upstream OpenCode titles - Delete backend/src/routes/title.ts and backend/src/services/session-title.ts - Remove /api/generate-title route from backend/src/index.ts - Delete backend/test/routes/title.test.ts - Remove useTitleGenerating hook and title generation logic from frontend/src/hooks/useOpenCode.ts - Remove generating prop from Header.EditableTitle and frontend/src/pages/SessionDetail.tsx - Clean up unused imports in frontend/src/hooks/useOpenCode.ts and frontend/src/components/ui/header.tsx - Session titles now come directly from upstream OpenCode via session refetches after prompt * refactor: optimize session query updates with setQueryData - Remove redundant query invalidations in useSendPrompt - Use setQueryData for optimistic updates in SSE session.updated handler - Update session cache directly when session exists in list - Prepend new sessions to list when not found - Fall back to invalidation only when cache is empty
This commit is contained in:
1 parent
6d961ccd72
commit
8e90ba2e6e
8 files changed
+40
-487
No files matched your search
@@ -26,7 +26,6 @@ async function getAppVersion(): Promise<string> {
|
||||
}
|
||||
import { createProvidersRoutes } from './routes/providers'
|
||||
import { createOAuthRoutes } from './routes/oauth'
|
||||
import { createTitleRoutes } from './routes/title'
|
||||
import { createSSERoutes } from './routes/sse'
|
||||
import { createSSHRoutes } from './routes/ssh'
|
||||
import { createNotificationRoutes } from './routes/notifications'
|
||||
@@ -266,7 +265,6 @@ protectedApi.route('/providers', createProvidersRoutes())
|
||||
protectedApi.route('/oauth', createOAuthRoutes())
|
||||
protectedApi.route('/tts', createTTSRoutes(db))
|
||||
protectedApi.route('/stt', createSTTRoutes(db))
|
||||
protectedApi.route('/generate-title', createTitleRoutes())
|
||||
protectedApi.route('/sse', createSSERoutes())
|
||||
protectedApi.route('/ssh', createSSHRoutes(gitAuthService))
|
||||
protectedApi.route('/notifications', createNotificationRoutes(notificationService))
|
||||
|
||||
@@ -1,228 +0,0 @@
|
||||
import { Hono } from 'hono'
|
||||
import { z } from 'zod'
|
||||
import { logger } from '../utils/logger'
|
||||
import { resolveOpenCodeModel } from '../services/opencode-models'
|
||||
import { OPENCODE_SERVER_URL } from '../services/proxy'
|
||||
|
||||
const TitleRequestSchema = z.object({
|
||||
text: z.string().min(1).max(5000),
|
||||
sessionID: z.string().min(1)
|
||||
})
|
||||
const TITLE_POLL_INTERVAL_MS = 1_000
|
||||
const TITLE_POLL_TIMEOUT_MS = 30_000
|
||||
|
||||
interface PromptResponse {
|
||||
parts?: Array<{ type?: string; text?: string }>
|
||||
}
|
||||
|
||||
interface SessionMessage {
|
||||
info?: {
|
||||
role?: string
|
||||
time?: {
|
||||
completed?: number
|
||||
}
|
||||
error?: {
|
||||
name?: string
|
||||
data?: {
|
||||
message?: string
|
||||
}
|
||||
}
|
||||
}
|
||||
parts?: Array<{ type?: string; text?: string }>
|
||||
}
|
||||
|
||||
function buildUrl(path: string, directory?: string): string {
|
||||
const url = `${OPENCODE_SERVER_URL}${path}`
|
||||
return directory ? `${url}${url.includes('?') ? '&' : '?'}directory=${encodeURIComponent(directory)}` : url
|
||||
}
|
||||
|
||||
function parsePromptResponse(responseText: string): PromptResponse | null {
|
||||
if (!responseText.trim()) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(responseText) as PromptResponse
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function extractText(parts: Array<{ type?: string; text?: string }> | undefined): string {
|
||||
return (parts ?? [])
|
||||
.filter((part) => part.type === 'text' && typeof part.text === 'string')
|
||||
.map((part) => part.text?.replace(/<think>[\s\S]*?<\/think>\s*/g, '').trim() ?? '')
|
||||
.filter(Boolean)
|
||||
.join('\n')
|
||||
}
|
||||
|
||||
function extractTitle(result: PromptResponse | SessionMessage): string {
|
||||
const text = extractText(result.parts)
|
||||
const title = text
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.find((line) => line.length > 0) || ''
|
||||
|
||||
if (title.length > 100) {
|
||||
return title.substring(0, 97) + '...'
|
||||
}
|
||||
|
||||
return title
|
||||
}
|
||||
|
||||
async function waitForTitleResponse(sessionID: string, directory: string): Promise<SessionMessage> {
|
||||
const startedAt = Date.now()
|
||||
|
||||
while (Date.now() - startedAt < TITLE_POLL_TIMEOUT_MS) {
|
||||
const messagesResponse = await fetch(buildUrl(`/session/${sessionID}/message`, directory))
|
||||
|
||||
if (!messagesResponse.ok) {
|
||||
const errorText = await messagesResponse.text()
|
||||
throw new Error(errorText || 'Failed to fetch title generation messages')
|
||||
}
|
||||
|
||||
const messages = await messagesResponse.json() as SessionMessage[]
|
||||
const assistantMessage = [...messages]
|
||||
.reverse()
|
||||
.find((message) => message.info?.role === 'assistant')
|
||||
|
||||
if (assistantMessage) {
|
||||
const errorText = assistantMessage.info?.error?.data?.message ?? assistantMessage.info?.error?.name
|
||||
if (errorText) {
|
||||
throw new Error(errorText)
|
||||
}
|
||||
|
||||
if (assistantMessage.info?.time?.completed) {
|
||||
return assistantMessage
|
||||
}
|
||||
}
|
||||
|
||||
await Bun.sleep(TITLE_POLL_INTERVAL_MS)
|
||||
}
|
||||
|
||||
throw new Error('Timed out waiting for title generation')
|
||||
}
|
||||
|
||||
const TITLE_PROMPT = `You are a title generator. You output ONLY a thread title. Nothing else.
|
||||
|
||||
<task>
|
||||
Generate a brief title that would help the user find this conversation later.
|
||||
|
||||
Follow all rules in <rules>
|
||||
Use the <examples> so you know what a good title looks like.
|
||||
Your output must be:
|
||||
- A single line
|
||||
- ≤50 characters
|
||||
- No explanations
|
||||
</task>
|
||||
|
||||
<rules>
|
||||
- Focus on the main topic or question the user needs to retrieve
|
||||
- Use -ing verbs for actions (Debugging, Implementing, Analyzing)
|
||||
- Keep exact: technical terms, numbers, filenames, HTTP codes
|
||||
- Remove: the, this, my, a, an
|
||||
- Never assume tech stack
|
||||
- Never use tools
|
||||
- NEVER respond to questions, just generate a title for the conversation
|
||||
- The title should NEVER include "summarizing" or "generating" when generating a title
|
||||
- DO NOT SAY YOU CANNOT GENERATE A TITLE OR COMPLAIN ABOUT THE INPUT
|
||||
- Always output something meaningful, even if the input is minimal.
|
||||
- If the user message is short or conversational (e.g. "hello", "lol", "whats up", "hey"):
|
||||
→ create a title that reflects the user's tone or intent (such as Greeting, Quick check-in, Light chat, Intro message, etc.)
|
||||
</rules>
|
||||
|
||||
<examples>
|
||||
"debug 500 errors in production" → Debugging production 500 errors
|
||||
"refactor user service" → Refactoring user service
|
||||
"why is app.js failing" → Analyzing app.js failure
|
||||
"implement rate limiting" → Implementing rate limiting
|
||||
"how do I connect postgres to my API" → Connecting Postgres to API
|
||||
"best practices for React hooks" → React hooks best practices
|
||||
</examples>`
|
||||
|
||||
export function createTitleRoutes() {
|
||||
const app = new Hono()
|
||||
|
||||
app.post('/', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json()
|
||||
const { text, sessionID } = TitleRequestSchema.parse(body)
|
||||
const directory = c.req.header('directory') || ''
|
||||
|
||||
logger.info('Generating session title via LLM', { sessionID, textLength: text.length })
|
||||
|
||||
const model = await resolveOpenCodeModel(directory || undefined, {
|
||||
preferSmallModel: true,
|
||||
})
|
||||
|
||||
const titleSessionResponse = await fetch(buildUrl('/session', directory), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title: 'Title Generation' })
|
||||
})
|
||||
|
||||
if (!titleSessionResponse.ok) {
|
||||
logger.error('Failed to create title generation session')
|
||||
return c.json({ error: 'Failed to create session' }, 500)
|
||||
}
|
||||
|
||||
const titleSession = await titleSessionResponse.json() as { id: string }
|
||||
const titleSessionID = titleSession.id
|
||||
|
||||
try {
|
||||
const promptResponse = await fetch(buildUrl(`/session/${titleSessionID}/message`, directory), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
parts: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `${TITLE_PROMPT}\n\nGenerate a title for this conversation:\n<user_message>\n${text.substring(0, 2000)}\n</user_message>`
|
||||
}
|
||||
],
|
||||
model: {
|
||||
providerID: model.providerID,
|
||||
modelID: model.modelID,
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
if (!promptResponse.ok) {
|
||||
const errorText = await promptResponse.text()
|
||||
logger.error('Failed to generate title via LLM', { error: errorText })
|
||||
return c.json({ error: 'LLM request failed' }, 500)
|
||||
}
|
||||
|
||||
const promptBody = await promptResponse.text()
|
||||
const promptResult = parsePromptResponse(promptBody)
|
||||
const title = extractTitle(promptResult ?? await waitForTitleResponse(titleSessionID, directory))
|
||||
|
||||
if (title) {
|
||||
const updateResponse = await fetch(buildUrl(`/session/${sessionID}`, directory), {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ title })
|
||||
})
|
||||
|
||||
if (!updateResponse.ok) {
|
||||
logger.error('Failed to update session title')
|
||||
}
|
||||
}
|
||||
|
||||
logger.info('Session title generated', { sessionID, title })
|
||||
return c.json({ title })
|
||||
|
||||
} finally {
|
||||
fetch(buildUrl(`/session/${titleSessionID}`, directory), {
|
||||
method: 'DELETE'
|
||||
}).catch(() => {})
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Failed to generate session title:', error)
|
||||
return c.json({ error: error instanceof Error ? error.message : 'Failed to generate title' }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
resolveOpenCodeModel: vi.fn(),
|
||||
fetch: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../../src/services/opencode-models', () => ({
|
||||
resolveOpenCodeModel: mocks.resolveOpenCodeModel,
|
||||
}))
|
||||
|
||||
vi.mock('../../src/utils/logger', () => ({
|
||||
logger: {
|
||||
info: vi.fn(),
|
||||
error: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@opencode-manager/shared/config/env', () => ({
|
||||
ENV: {
|
||||
OPENCODE: { PORT: 5551, HOST: '127.0.0.1' },
|
||||
},
|
||||
}))
|
||||
|
||||
import { createTitleRoutes } from '../../src/routes/title'
|
||||
|
||||
function jsonResponse(body: unknown, status: number = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
function textResponse(body: string, status: number = 200): Response {
|
||||
return new Response(body, { status })
|
||||
}
|
||||
|
||||
describe('Title Routes', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.resolveOpenCodeModel.mockResolvedValue({ providerID: 'openai', modelID: 'gpt-5-mini' })
|
||||
vi.stubGlobal('fetch', mocks.fetch)
|
||||
vi.stubGlobal('Bun', { sleep: mocks.sleep })
|
||||
mocks.sleep.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('updates the session title from an immediate JSON prompt response', async () => {
|
||||
const app = createTitleRoutes()
|
||||
|
||||
mocks.fetch
|
||||
.mockResolvedValueOnce(jsonResponse({ id: 'title-session-1' }))
|
||||
.mockResolvedValueOnce(textResponse(JSON.stringify({
|
||||
parts: [{ type: 'text', text: 'Refactoring background jobs' }],
|
||||
})))
|
||||
.mockResolvedValueOnce(textResponse('', 200))
|
||||
.mockResolvedValueOnce(textResponse('', 200))
|
||||
|
||||
const response = await app.request('http://localhost/', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
directory: '/workspace/repos/sample-project',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
text: 'Refactor recurring background jobs and improve observability.',
|
||||
sessionID: 'session-main-1',
|
||||
}),
|
||||
})
|
||||
const body = await response.json() as { title: string }
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.title).toBe('Refactoring background jobs')
|
||||
expect(mocks.fetch).toHaveBeenCalledWith(
|
||||
'http://127.0.0.1:5551/session/session-main-1?directory=%2Fworkspace%2Frepos%2Fsample-project',
|
||||
expect.objectContaining({ method: 'PATCH' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('polls session messages when the prompt endpoint returns an empty body', async () => {
|
||||
const app = createTitleRoutes()
|
||||
|
||||
mocks.fetch
|
||||
.mockResolvedValueOnce(jsonResponse({ id: 'title-session-2' }))
|
||||
.mockResolvedValueOnce(textResponse(''))
|
||||
.mockResolvedValueOnce(jsonResponse([
|
||||
{
|
||||
info: { role: 'assistant', time: { completed: Date.now() } },
|
||||
parts: [{ type: 'text', text: 'Analyzing recurring job setup' }],
|
||||
},
|
||||
]))
|
||||
.mockResolvedValueOnce(textResponse('', 200))
|
||||
.mockResolvedValueOnce(textResponse('', 200))
|
||||
|
||||
const response = await app.request('http://localhost/', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
directory: '/workspace/repos/sample-project',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
text: 'Why do recurring jobs stop after a restart?',
|
||||
sessionID: 'session-main-2',
|
||||
}),
|
||||
})
|
||||
const body = await response.json() as { title: string }
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body.title).toBe('Analyzing recurring job setup')
|
||||
expect(mocks.fetch).toHaveBeenNthCalledWith(
|
||||
3,
|
||||
'http://127.0.0.1:5551/session/title-session-2/message?directory=%2Fworkspace%2Frepos%2Fsample-project',
|
||||
)
|
||||
})
|
||||
|
||||
it('returns a 500 when the polled assistant message reports an error', async () => {
|
||||
const app = createTitleRoutes()
|
||||
|
||||
mocks.fetch
|
||||
.mockResolvedValueOnce(jsonResponse({ id: 'title-session-3' }))
|
||||
.mockResolvedValueOnce(textResponse(''))
|
||||
.mockResolvedValueOnce(jsonResponse([
|
||||
{
|
||||
info: {
|
||||
role: 'assistant',
|
||||
error: { data: { message: 'Model unavailable' } },
|
||||
},
|
||||
parts: [],
|
||||
},
|
||||
]))
|
||||
.mockResolvedValueOnce(textResponse('', 200))
|
||||
|
||||
const response = await app.request('http://localhost/', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
directory: '/workspace/repos/sample-project',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
text: 'Generate a title for this broken run.',
|
||||
sessionID: 'session-main-3',
|
||||
}),
|
||||
})
|
||||
const body = await response.json() as { error: string }
|
||||
|
||||
expect(response.status).toBe(500)
|
||||
expect(body.error).toBe('Model unavailable')
|
||||
})
|
||||
})
|
||||
@@ -10,7 +10,7 @@ import { cn } from "@/lib/utils";
|
||||
import type { ReactNode } from "react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useMobile } from "@/hooks/useMobile";
|
||||
import { Loader2, X } from "lucide-react";
|
||||
import { X } from "lucide-react";
|
||||
import { usePermissions, useQuestions } from "@/contexts/EventContext";
|
||||
|
||||
interface HeaderProps {
|
||||
@@ -62,11 +62,10 @@ interface HeaderEditableTitleProps {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
subtitle?: React.ReactNode;
|
||||
generating?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
function HeaderEditableTitle({ value, onChange, subtitle, generating, className }: HeaderEditableTitleProps) {
|
||||
function HeaderEditableTitle({ value, onChange, subtitle, className }: HeaderEditableTitleProps) {
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [editTitle, setEditTitle] = useState(value);
|
||||
const isMobile = useMobile();
|
||||
@@ -143,19 +142,12 @@ function HeaderEditableTitle({ value, onChange, subtitle, generating, className
|
||||
</form>
|
||||
) : (
|
||||
<div className="min-w-0">
|
||||
{generating ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Loader2 className="w-3 h-3 animate-spin text-muted-foreground" />
|
||||
<span className="text-xs sm:text-base text-muted-foreground italic">Generating title...</span>
|
||||
</div>
|
||||
) : (
|
||||
<h1
|
||||
className="text-xs sm:text-base font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent truncate cursor-pointer hover:opacity-80 transition-opacity"
|
||||
onClick={handleTitleClick}
|
||||
>
|
||||
{value}
|
||||
</h1>
|
||||
)}
|
||||
<h1
|
||||
className="text-xs sm:text-base font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent truncate cursor-pointer hover:opacity-80 transition-opacity"
|
||||
onClick={handleTitleClick}
|
||||
>
|
||||
{value}
|
||||
</h1>
|
||||
{subtitle && (
|
||||
<p className="text-[10px] sm:text-xs text-muted-foreground truncate">
|
||||
{typeof subtitle === 'string' ? subtitle : subtitle}
|
||||
@@ -254,4 +246,4 @@ export const Header = Object.assign(HeaderBase, {
|
||||
Actions: typeof HeaderActions;
|
||||
MobileDropdown: typeof HeaderMobileDropdown;
|
||||
Settings: typeof HeaderSettingsButton;
|
||||
};
|
||||
};
|
||||
@@ -1,8 +1,7 @@
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useMemo, useRef, useEffect, useCallback, useState } from "react";
|
||||
import { useMemo, useRef, useEffect, useCallback } from "react";
|
||||
import { OpenCodeClient } from "../api/opencode";
|
||||
import { API_BASE_URL } from "../config";
|
||||
import { fetchWrapper, FetchError } from "../api/fetchWrapper";
|
||||
import { FetchError } from "../api/fetchWrapper";
|
||||
import { cancelLoop } from "../api/memory";
|
||||
import type {
|
||||
Message,
|
||||
@@ -16,33 +15,6 @@ import { showToast } from "../lib/toast";
|
||||
import { useSessionStatus } from "../stores/sessionStatusStore";
|
||||
import { ensureSSEConnected, reconnectSSE } from "../lib/sseManager";
|
||||
|
||||
const titleGeneratingSessionsState = new Set<string>();
|
||||
const titleGeneratingListeners = new Set<() => void>();
|
||||
|
||||
function notifyTitleGeneratingListeners() {
|
||||
titleGeneratingListeners.forEach(listener => listener());
|
||||
}
|
||||
|
||||
export function useTitleGenerating(sessionID: string | undefined) {
|
||||
const [isGenerating, setIsGenerating] = useState(
|
||||
sessionID ? titleGeneratingSessionsState.has(sessionID) : false
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setIsGenerating(sessionID ? titleGeneratingSessionsState.has(sessionID) : false);
|
||||
|
||||
const listener = () => {
|
||||
setIsGenerating(sessionID ? titleGeneratingSessionsState.has(sessionID) : false);
|
||||
};
|
||||
titleGeneratingListeners.add(listener);
|
||||
return () => {
|
||||
titleGeneratingListeners.delete(listener);
|
||||
};
|
||||
}, [sessionID]);
|
||||
|
||||
return isGenerating;
|
||||
}
|
||||
|
||||
type AssistantMessage = components["schemas"]["AssistantMessage"];
|
||||
|
||||
type SendPromptRequest = NonNullable<
|
||||
@@ -233,44 +205,8 @@ const createOptimisticUserMessageInfo = (
|
||||
export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?: string) => {
|
||||
const client = useOpenCodeClient(opcodeUrl, directory);
|
||||
const queryClient = useQueryClient();
|
||||
const hasInitializedRef = useRef<Set<string>>(new Set());
|
||||
const setSessionStatus = useSessionStatus((state) => state.setStatus);
|
||||
|
||||
const generateSessionTitle = async (sessionID: string, userPromptText: string) => {
|
||||
if (!client || hasInitializedRef.current.has(sessionID)) return;
|
||||
|
||||
try {
|
||||
const session = await client.getSession(sessionID);
|
||||
const isDefaultTitle = session.title.match(/^New session - \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/);
|
||||
|
||||
if (isDefaultTitle && userPromptText) {
|
||||
titleGeneratingSessionsState.add(sessionID);
|
||||
notifyTitleGeneratingListeners();
|
||||
|
||||
try {
|
||||
await fetchWrapper(`${API_BASE_URL}/api/generate-title`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", directory: directory || "" },
|
||||
body: JSON.stringify({ text: userPromptText, sessionID }),
|
||||
});
|
||||
|
||||
hasInitializedRef.current.add(sessionID);
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["opencode", "session", opcodeUrl, sessionID, directory],
|
||||
});
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["opencode", "sessions", opcodeUrl, directory],
|
||||
});
|
||||
} finally {
|
||||
titleGeneratingSessionsState.delete(sessionID);
|
||||
notifyTitleGeneratingListeners();
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Silently fail - title generation is a background task
|
||||
}
|
||||
};
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({
|
||||
sessionID,
|
||||
@@ -300,8 +236,6 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
const optimisticUserID = `optimistic_user_${Date.now()}_${Math.random()}`;
|
||||
|
||||
const contentParts = parts || [{ type: "text" as const, content: prompt || "", name: "" }];
|
||||
const userPromptText = prompt || (contentParts[0] as ContentPart & { type: "text" })?.content || "";
|
||||
|
||||
const userMessageParts = createOptimisticUserMessageParts(
|
||||
sessionID,
|
||||
contentParts,
|
||||
@@ -363,7 +297,7 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
|
||||
const response = await client.sendPrompt(sessionID, requestData);
|
||||
|
||||
return { optimisticUserID, userPromptText, response };
|
||||
return { optimisticUserID, response };
|
||||
},
|
||||
onError: (error, variables) => {
|
||||
const { sessionID } = variables;
|
||||
@@ -397,7 +331,7 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
},
|
||||
onSuccess: async (data, variables) => {
|
||||
const { sessionID } = variables;
|
||||
const { optimisticUserID, userPromptText, response } = data;
|
||||
const { optimisticUserID, response } = data;
|
||||
const messagesQueryKey = ["opencode", "messages", opcodeUrl, sessionID, directory];
|
||||
|
||||
queryClient.setQueryData<MessageWithParts[]>(
|
||||
@@ -418,12 +352,6 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?:
|
||||
);
|
||||
|
||||
setSessionStatus(sessionID, { type: "idle" });
|
||||
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["opencode", "session", opcodeUrl, sessionID, directory],
|
||||
});
|
||||
|
||||
await generateSessionTitle(sessionID, userPromptText);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useEffect, useRef, useState, useCallback } from 'react'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { useOpenCodeClient } from './useOpenCode'
|
||||
import type { SSEEvent, MessageWithParts } from '@/api/types'
|
||||
import type { SSEEvent, MessageWithParts, Session } from '@/api/types'
|
||||
import { showToast } from '@/lib/toast'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
@@ -71,12 +71,27 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string,
|
||||
const handleSSEEvent = useCallback((event: SSEEvent) => {
|
||||
switch (event.type) {
|
||||
case 'session.updated':
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'sessions', opcodeUrl, directory] })
|
||||
if ('info' in event.properties) {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['opencode', 'session', opcodeUrl, event.properties.info.id, directory]
|
||||
})
|
||||
const session = event.properties.info
|
||||
const sessionQueryKey = ['opencode', 'session', opcodeUrl, session.id, directory]
|
||||
const sessionsQueryKey = ['opencode', 'sessions', opcodeUrl, directory]
|
||||
|
||||
queryClient.setQueryData(sessionQueryKey, session)
|
||||
|
||||
const sessions = queryClient.getQueryData<Session[]>(sessionsQueryKey)
|
||||
if (sessions) {
|
||||
const exists = sessions.some((item) => item.id === session.id)
|
||||
const updated = exists
|
||||
? sessions.map((item) => (item.id === session.id ? session : item))
|
||||
: [session, ...sessions]
|
||||
queryClient.setQueryData(sessionsQueryKey, updated)
|
||||
break
|
||||
}
|
||||
|
||||
queryClient.invalidateQueries({ queryKey: sessionsQueryKey })
|
||||
break
|
||||
}
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode', 'sessions', opcodeUrl, directory] })
|
||||
break
|
||||
|
||||
case 'session.deleted':
|
||||
|
||||
@@ -15,7 +15,7 @@ import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
|
||||
import { ContextUsageIndicator } from "@/components/session/ContextUsageIndicator";
|
||||
import { useSession, useAbortSession, useUpdateSession, useMessages, useTitleGenerating, useCreateSession } from "@/hooks/useOpenCode";
|
||||
import { useSession, useAbortSession, useUpdateSession, useMessages, useCreateSession } from "@/hooks/useOpenCode";
|
||||
import { useRepoActivity } from "@/hooks/useRepoActivity";
|
||||
import { OPENCODE_API_ENDPOINT } from "@/config";
|
||||
import { useSSE } from "@/hooks/useSSE";
|
||||
@@ -142,7 +142,6 @@ export function SessionDetail() {
|
||||
const abortSession = useAbortSession(opcodeUrl, repoDirectory, sessionId);
|
||||
const updateSession = useUpdateSession(opcodeUrl, repoDirectory);
|
||||
const createSession = useCreateSession(opcodeUrl, repoDirectory);
|
||||
const isTitleGenerating = useTitleGenerating(sessionId);
|
||||
const { model, modelString } = useModelSelection(opcodeUrl, repoDirectory);
|
||||
const isEditingMessage = useUIState((state) => state.isEditingMessage);
|
||||
const { isEnabled: ttsEnabled } = useTTS();
|
||||
@@ -380,12 +379,11 @@ export function SessionDetail() {
|
||||
) : (
|
||||
<Header.BackButton to={`/repos/${repoId}`} className="text-xs sm:text-sm" />
|
||||
)}
|
||||
<Header.EditableTitle
|
||||
value={session?.title || "Untitled Session"}
|
||||
onChange={handleSessionTitleUpdate}
|
||||
subtitle={<span className="text-orange-600 dark:text-orange-400">{getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath)}</span>}
|
||||
generating={isTitleGenerating}
|
||||
/>
|
||||
<Header.EditableTitle
|
||||
value={session?.title || "Untitled Session"}
|
||||
onChange={handleSessionTitleUpdate}
|
||||
subtitle={<span className="text-orange-600 dark:text-orange-400">{getRepoDisplayName(repo.repoUrl, repo.localPath, repo.sourcePath)}</span>}
|
||||
/>
|
||||
</div>
|
||||
<Header.Actions className="gap-2 sm:gap-4">
|
||||
<div className="hidden sm:flex items-center gap-1">
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "opencode-manager",
|
||||
"version": "0.9.15",
|
||||
"version": "0.9.16",
|
||||
"private": false,
|
||||
"type": "module",
|
||||
"packageManager": "pnpm@10.28.1",
|
||||
|
||||
Reference in new issue
Block a user