mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 04:44:21 +01:00
Add AI-generated session titles with loading indicator and debouncing
This commit is contained in:
1 parent
ec10be823e
commit
6af39af424
6 files changed
+268
-14
No files matched your search
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
<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 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<user_message>\n${text.substring(0, 2000)}\n</user_message>`
|
||||
}
|
||||
],
|
||||
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(/<think>[\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
|
||||
}
|
||||
@@ -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<HTMLInputElement>(null);
|
||||
const isMobile = useMobile();
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setEditTitle(currentTitle);
|
||||
}
|
||||
}, [isOpen, currentTitle]);
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Escape') {
|
||||
setEditTitle(currentTitle);
|
||||
|
||||
@@ -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 (
|
||||
<div className="sticky top-0 z-10 border-b border-border bg-gradient-to-b from-background via-background to-background backdrop-blur-sm px-2 sm:px-4 py-1.5 sm:py-2">
|
||||
@@ -164,12 +172,19 @@ export function SessionDetailHeader({
|
||||
</form>
|
||||
) : (
|
||||
<>
|
||||
<h1
|
||||
className="text-xs text-green-500 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}
|
||||
>
|
||||
{sessionTitle}
|
||||
</h1>
|
||||
{isTitleGenerating ? (
|
||||
<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 text-green-500 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}
|
||||
>
|
||||
{sessionTitle}
|
||||
</h1>
|
||||
)}
|
||||
<p className="text-[10px] sm:text-xs text-green-600 dark:text-green-400 truncate">
|
||||
{repoName}
|
||||
</p>
|
||||
|
||||
@@ -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<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(() => {
|
||||
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<Set<string>>(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<MessageListResponse>(
|
||||
["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);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@@ -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)}
|
||||
|
||||
Reference in new issue
Block a user