Files
platform/src/apps/officer-web/state/useSessions.ts
T

54 lines
2.3 KiB
TypeScript

import type { SessionEntry, ChatMessage } from 'plugins/Chat/client';
import type { SlashCommandResult } from './useSlashCommands';
import { useAuth } from 'hooks/useAuth';
import { useClient } from 'hooks/useClient';
import { useQuery, useQueryClient } from '@tanstack/react-query';
export const useSessions = () => {
type RawSessionEntry = Omit<SessionEntry, 'provider'>;
const client = useClient();
const queryClient = useQueryClient();
const { isAuthenticated } = useAuth();
const { data: sessions = [] } = useQuery<RawSessionEntry[], Error, SessionEntry[]>({
queryKey: ['SESSIONS'],
enabled: isAuthenticated,
queryFn: () => client.get<RawSessionEntry[]>('/sessions'),
select: (data) => data.map((s) => ({ ...s, provider: 'claude' as const })),
});
const getMessages = (sessionId: string) => client.get<ChatMessage[]>(`/sessions/${sessionId}/messages`);
const saveMessages = (sessionId: string, messages: ChatMessage[]) =>
client.put(`/sessions/${sessionId}/messages`, messages);
const renameSession = async (sessionId: string | null, args: string): Promise<SlashCommandResult> => {
if (!args) return { handled: true, feedback: 'Usage: /rename <new title>' };
if (!sessionId) return { handled: true, feedback: 'No active session to rename.' };
const title = args.slice(0, 200);
try {
await client.put(`/sessions/${sessionId}`, { title });
queryClient.setQueryData<SessionEntry[]>(
['SESSIONS'],
(prev) => prev?.map((s) => (s.id === sessionId ? { ...s, title } : s)) ?? [],
);
return { handled: true, feedback: `Session renamed to "${title}"` };
} catch {
return { handled: true, feedback: 'Failed to rename session.' };
}
};
const archiveSession = async (sessionId: string) => {
await client.post(`/sessions/${sessionId}/archive`);
queryClient.setQueryData<SessionEntry[]>(['SESSIONS'], (prev) => prev?.filter((s) => s.id !== sessionId) ?? []);
};
const deleteSession = async (sessionId: string) => {
await client.delete(`/sessions/${sessionId}`);
queryClient.setQueryData<SessionEntry[]>(['SESSIONS'], (prev) => prev?.filter((s) => s.id !== sessionId) ?? []);
};
return { sessions, getMessages, saveMessages, renameSession, archiveSession, deleteSession };
};