okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fa6367a98
main
1import { useEffect , useSyncExternalStore } from 'react' ; 2import { api } from './client' ; 3import { postWithFolderFallback } from './folder-pick' ; 4 5/** A chat's project folder (notes-split-agent8.md, item 4): the assistant works inside it and can only touch files in it. */ 6export interface ChatFolder { path :string ; name :string ; exists :boolean } 7const folders = new Map < string , ChatFolder | null >(); 8const listeners = new Set <() => void >(); 9const subscribe = ( fn :() => void ) => { listeners . add ( fn ); return () => { listeners . delete ( fn ); }; }; 10const emit = () => listeners . forEach ( fn => fn ()); 11 12export function readFolder ( raw :unknown ) :ChatFolder | null { 13if ( ! raw || typeof raw !== 'object' ) return null ; 14const f = raw as Record < string , unknown >; 15if ( typeof f . path !== 'string' || ! f . path ) return null ; 16return { path :f . path , name :typeof f . name === 'string' && f . name ?f . name :f . path . split ( / [\/] / ). filter ( Boolean ). at ( - 1 ) ?? f . path , exists :f . exists !== false }; 17} 18 19function put ( chatId :string , folder :ChatFolder | null ) { 20if ( JSON . stringify ( folders . get ( chatId ) ?? null ) === JSON . stringify ( folder ) && folders . has ( chatId )) return ; 21folders . set ( chatId , folder ); emit (); 22} 23 24export const folderOf = ( chatId :string | null | undefined ) => ( chatId ?folders . get ( chatId ) ?? null :null ); 25 26export function useChatFolder ( chatId :string | null | undefined ) :ChatFolder | null { 27const value = useSyncExternalStore ( subscribe , () => folderOf ( chatId ), () => null ); 28useEffect (() => { if ( chatId ) void loadFolder ( chatId ); }, [ chatId ]); 29return value ; 30} 31 32export async function loadFolder ( chatId :string ) { 33try { put ( chatId , readFolder (( await api . get <{ folder :unknown }>( `/api/chat/folder?sessionId= ${ encodeURIComponent ( chatId )} ` )). folder )); } 34catch { /* an older host has no folder route: no chip */ } 35} 36 37/** Ask the system for a folder (null when the person closes the dialog), then make it this chat's. */ 38export async function chooseChatFolder ( chatId :string ) :Promise < 'chosen' | 'cancelled' > { 39const picked = await postWithFolderFallback <{ path ?:string ; cancelled ?:boolean }>( '/api/workspaces/pick' ) as { path ?:string }; 40if ( ! picked . path ) return 'cancelled' ; 41await setChatFolder ( chatId , picked . path ); 42return 'chosen' ; 43} 44 45/** `null` goes back to the default workspace. The host answers a plain sentence when the folder is not allowed (409 while the chat runs). */ 46export async function setChatFolder ( chatId :string , path :string | null ) { 47const result = await api . post <{ folder :unknown }>( '/api/chat/folder' , { sessionId :chatId , path}); 48put ( chatId , readFolder ( result . folder )); 49}