diff --git a/backend/src/index.ts b/backend/src/index.ts index 3ef5bbf4..c50e6ba2 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -12,6 +12,7 @@ import { createTTSRoutes, cleanupExpiredCache } from './routes/tts' import { createFileRoutes } from './routes/files' import { createProvidersRoutes } from './routes/providers' import { createOAuthRoutes } from './routes/oauth' +import { createTitleRoutes } from './routes/title' import { ensureDirectoryExists, writeFileContent, fileExists, readFileContent } from './services/file-operations' import { SettingsService } from './services/settings' import { opencodeServerManager } from './services/opencode-single-server' @@ -228,6 +229,7 @@ app.route('/api/files', createFileRoutes(db)) app.route('/api/providers', createProvidersRoutes()) app.route('/api/oauth', createOAuthRoutes()) app.route('/api/tts', createTTSRoutes(db)) +app.route('/api/generate-title', createTitleRoutes()) app.all('/api/opencode/*', async (c) => { const request = c.req.raw diff --git a/backend/src/routes/title.ts b/backend/src/routes/title.ts new file mode 100644 index 00000000..40d84e2b --- /dev/null +++ b/backend/src/routes/title.ts @@ -0,0 +1,162 @@ +import { Hono } from 'hono' +import { z } from 'zod' +import { logger } from '../utils/logger' +import { ENV } from '@opencode-manager/shared/config/env' + +const TitleRequestSchema = z.object({ + text: z.string().min(1).max(5000), + sessionID: z.string().min(1) +}) + +const OPENCODE_SERVER_URL = `http://127.0.0.1:${ENV.OPENCODE.PORT}` + +const TITLE_PROMPT = `You are a title generator. You output ONLY a thread title. Nothing else. + + +Generate a brief title that would help the user find this conversation later. + +Follow all rules in +Use the so you know what a good title looks like. +Your output must be: +- A single line +- ≤50 characters +- No explanations + + + +- 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.) + + + +"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 +` + +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 configResponse = await fetch(`${OPENCODE_SERVER_URL}/config`) + if (!configResponse.ok) { + logger.error('Failed to fetch OpenCode config') + return c.json({ error: 'Failed to fetch config' }, 500) + } + const config = await configResponse.json() as { model?: string; small_model?: string } + + const modelStr = config.small_model || config.model || 'anthropic/claude-3-haiku-20240307' + const [providerID, modelID] = modelStr.split('/') + + const titleSessionResponse = await fetch(`${OPENCODE_SERVER_URL}/session`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(directory && { directory }) + }, + 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(`${OPENCODE_SERVER_URL}/session/${titleSessionID}/message`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(directory && { directory }) + }, + body: JSON.stringify({ + parts: [ + { + type: 'text', + text: `${TITLE_PROMPT}\n\nGenerate a title for this conversation:\n\n${text.substring(0, 2000)}\n` + } + ], + model: { providerID, 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 result = await promptResponse.json() as { parts?: Array<{ type: string; text?: string }> } + + let title = '' + if (result.parts) { + const textPart = result.parts.find((p: { type: string }) => p.type === 'text') + if (textPart && 'text' in textPart) { + title = (textPart.text as string) + .replace(/[\s\S]*?<\/think>\s*/g, '') + .split('\n') + .map((line: string) => line.trim()) + .find((line: string) => line.length > 0) || '' + } + } + + if (title && title.length > 100) { + title = title.substring(0, 97) + '...' + } + + if (title) { + const updateResponse = await fetch(`${OPENCODE_SERVER_URL}/session/${sessionID}`, { + method: 'PATCH', + headers: { + 'Content-Type': 'application/json', + ...(directory && { directory }) + }, + 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(`${OPENCODE_SERVER_URL}/session/${titleSessionID}`, { + method: 'DELETE', + headers: directory ? { directory } : {} + }).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 +} diff --git a/frontend/src/components/session/EditSessionTitleDialog.tsx b/frontend/src/components/session/EditSessionTitleDialog.tsx index 9b43c6a6..306f74ec 100644 --- a/frontend/src/components/session/EditSessionTitleDialog.tsx +++ b/frontend/src/components/session/EditSessionTitleDialog.tsx @@ -1,7 +1,7 @@ import { Dialog, DialogContent } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { X, Check } from "lucide-react"; -import { useState, useRef } from "react"; +import { useState, useRef, useEffect } from "react"; import { useMobile } from "@/hooks/useMobile"; interface EditSessionTitleDialogProps { @@ -16,6 +16,12 @@ export function EditSessionTitleDialog({ isOpen, currentTitle, onClose, onSave } const inputRef = useRef(null); const isMobile = useMobile(); + useEffect(() => { + if (isOpen) { + setEditTitle(currentTitle); + } + }, [isOpen, currentTitle]); + const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Escape') { setEditTitle(currentTitle); diff --git a/frontend/src/components/session/SessionDetailHeader.tsx b/frontend/src/components/session/SessionDetailHeader.tsx index 6ceb9cfe..dc188d41 100644 --- a/frontend/src/components/session/SessionDetailHeader.tsx +++ b/frontend/src/components/session/SessionDetailHeader.tsx @@ -5,7 +5,7 @@ import { Button } from "@/components/ui/button"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"; import { EditSessionTitleDialog } from "@/components/session/EditSessionTitleDialog"; import { Loader2, Settings, CornerUpLeft, Plug, FolderOpen, MoreVertical, Upload, X } from "lucide-react"; -import { useState } from "react"; +import { useState, useEffect } from "react"; import { useMobile } from "@/hooks/useMobile"; interface Repo { @@ -29,6 +29,7 @@ interface SessionDetailHeaderProps { opcodeUrl: string | null; repoDirectory: string | undefined; parentSessionId?: string; + isTitleGenerating?: boolean; onFileBrowserOpen: () => void; onSettingsOpen: () => void; onMcpDialogOpen: () => void; @@ -47,6 +48,7 @@ export function SessionDetailHeader({ opcodeUrl, repoDirectory, parentSessionId, + isTitleGenerating, onFileBrowserOpen, onSettingsOpen, onMcpDialogOpen, @@ -58,6 +60,12 @@ export function SessionDetailHeader({ const isMobile = useMobile(); const [editTitle, setEditTitle] = useState(sessionTitle); + useEffect(() => { + if (!isEditing) { + setEditTitle(sessionTitle); + } + }, [sessionTitle, isEditing]); + if (repo.cloneStatus !== 'ready') { return (
@@ -164,12 +172,19 @@ export function SessionDetailHeader({ ) : ( <> -

- {sessionTitle} -

+ {isTitleGenerating ? ( +
+ + Generating title... +
+ ) : ( +

+ {sessionTitle} +

+ )}

{repoName}

diff --git a/frontend/src/hooks/useOpenCode.ts b/frontend/src/hooks/useOpenCode.ts index 9a48092c..780770e7 100644 --- a/frontend/src/hooks/useOpenCode.ts +++ b/frontend/src/hooks/useOpenCode.ts @@ -1,6 +1,7 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; -import { useMemo, useRef, useEffect, useCallback } from "react"; +import { useMemo, useRef, useEffect, useCallback, useState } from "react"; import { OpenCodeClient } from "../api/opencode"; +import { API_BASE_URL } from "../config"; import type { MessageWithParts, MessageListResponse, @@ -8,6 +9,31 @@ import type { } from "../api/types"; import type { paths, components } from "../api/opencode-types"; +const titleGeneratingSessionsState = new Set(); +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(() => { + 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< @@ -180,6 +206,44 @@ const createOptimisticUserMessage = ( export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?: string) => { const client = useOpenCodeClient(opcodeUrl, directory); const queryClient = useQueryClient(); + const hasInitializedRef = useRef>(new Set()); + + 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 { + const response = await fetch(`${API_BASE_URL}/api/generate-title`, { + method: "POST", + headers: { "Content-Type": "application/json", directory: directory || "" }, + body: JSON.stringify({ text: userPromptText, sessionID }), + }); + + if (response.ok) { + 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 (error) { + console.error("Failed to generate session title:", error); + } + }; return useMutation({ mutationFn: async ({ @@ -200,6 +264,7 @@ 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 userMessage = createOptimisticUserMessage( sessionID, @@ -214,7 +279,7 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?: const requestData: SendPromptRequest = { parts: parts?.map((part) => part.type === "text" - ? { type: "text", text: part.content } + ? { type: "text", text: (part as ContentPart & { type: "text" }).content } : part.type === "image" ? { type: "file", @@ -249,7 +314,7 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?: const response = await client.sendPrompt(sessionID, requestData); - return { optimisticUserID, response }; + return { optimisticUserID, response, userPromptText }; }, onError: (_, variables) => { const { sessionID } = variables; @@ -258,9 +323,9 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?: (old) => old?.filter((msg) => !msg.info.id.startsWith("optimistic_")), ); }, - onSuccess: (data, variables) => { + onSuccess: async (data, variables) => { const { sessionID } = variables; - const { optimisticUserID } = data; + const { optimisticUserID, userPromptText } = data; queryClient.setQueryData( ["opencode", "messages", opcodeUrl, sessionID, directory], @@ -270,6 +335,8 @@ export const useSendPrompt = (opcodeUrl: string | null | undefined, directory?: queryClient.invalidateQueries({ queryKey: ["opencode", "session", opcodeUrl, sessionID, directory], }); + + await generateSessionTitle(sessionID, userPromptText); }, }); }; diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index dca5f245..949736b6 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -11,7 +11,7 @@ import { SessionList } from "@/components/session/SessionList"; import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet"; import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"; -import { useSession, useAbortSession, useUpdateSession, useMessages } from "@/hooks/useOpenCode"; +import { useSession, useAbortSession, useUpdateSession, useMessages, useTitleGenerating } from "@/hooks/useOpenCode"; import { OPENCODE_API_ENDPOINT, API_BASE_URL } from "@/config"; import { useSSE } from "@/hooks/useSSE"; import { useUIState } from "@/stores/uiStateStore"; @@ -99,6 +99,7 @@ export function SessionDetail() { const { isConnected, isReconnecting } = useSSE(opcodeUrl, repoDirectory); const abortSession = useAbortSession(opcodeUrl, repoDirectory, sessionId); const updateSession = useUpdateSession(opcodeUrl, repoDirectory); + const isTitleGenerating = useTitleGenerating(sessionId); const { open: openSettings } = useSettingsDialog(); const { modelString } = useModelSelection(opcodeUrl, repoDirectory); const isEditingMessage = useUIState((state) => state.isEditingMessage); @@ -236,6 +237,7 @@ export function SessionDetail() { opcodeUrl={opcodeUrl} repoDirectory={repoDirectory} parentSessionId={session?.parentID} + isTitleGenerating={isTitleGenerating} onFileBrowserOpen={() => setFileBrowserOpen(true)} onSettingsOpen={openSettings} onMcpDialogOpen={() => setMcpDialogOpen(true)}