1+ import { DurableObject } from 'cloudflare:workers' ;
2+ import type { SessionInfo } from './types' ;
3+ import type { Env } from './core-utils' ;
4+
5+ // 🤖 AI Extension Point: Add session management features
6+ export class AppController extends DurableObject < Env > {
7+ private sessions = new Map < string , SessionInfo > ( ) ;
8+ private loaded = false ;
9+
10+ constructor ( ctx : DurableObjectState , env : Env ) {
11+ super ( ctx , env ) ;
12+ }
13+
14+ private async ensureLoaded ( ) : Promise < void > {
15+ if ( ! this . loaded ) {
16+ const stored = await this . ctx . storage . get < Record < string , SessionInfo > > ( 'sessions' ) || { } ;
17+ this . sessions = new Map ( Object . entries ( stored ) ) ;
18+ this . loaded = true ;
19+ }
20+ }
21+
22+ private async persist ( ) : Promise < void > {
23+ await this . ctx . storage . put ( 'sessions' , Object . fromEntries ( this . sessions ) ) ;
24+ }
25+
26+ async addSession ( sessionId : string , title ?: string ) : Promise < void > {
27+ await this . ensureLoaded ( ) ;
28+ const now = Date . now ( ) ;
29+ this . sessions . set ( sessionId , {
30+ id : sessionId ,
31+ title : title || `Chat ${ new Date ( now ) . toLocaleDateString ( ) } ` ,
32+ createdAt : now ,
33+ lastActive : now
34+ } ) ;
35+ await this . persist ( ) ;
36+ }
37+
38+ async removeSession ( sessionId : string ) : Promise < boolean > {
39+ await this . ensureLoaded ( ) ;
40+ const deleted = this . sessions . delete ( sessionId ) ;
41+ if ( deleted ) await this . persist ( ) ;
42+ return deleted ;
43+ }
44+
45+ async updateSessionActivity ( sessionId : string ) : Promise < void > {
46+ await this . ensureLoaded ( ) ;
47+ const session = this . sessions . get ( sessionId ) ;
48+ if ( session ) {
49+ session . lastActive = Date . now ( ) ;
50+ await this . persist ( ) ;
51+ }
52+ }
53+
54+ async updateSessionTitle ( sessionId : string , title : string ) : Promise < boolean > {
55+ await this . ensureLoaded ( ) ;
56+ const session = this . sessions . get ( sessionId ) ;
57+ if ( session ) {
58+ session . title = title ;
59+ await this . persist ( ) ;
60+ return true ;
61+ }
62+ return false ;
63+ }
64+
65+ async listSessions ( ) : Promise < SessionInfo [ ] > {
66+ await this . ensureLoaded ( ) ;
67+ return Array . from ( this . sessions . values ( ) ) . sort ( ( a , b ) => b . lastActive - a . lastActive ) ;
68+ }
69+
70+ async getSessionCount ( ) : Promise < number > {
71+ await this . ensureLoaded ( ) ;
72+ return this . sessions . size ;
73+ }
74+
75+ async getSession ( sessionId : string ) : Promise < SessionInfo | null > {
76+ await this . ensureLoaded ( ) ;
77+ return this . sessions . get ( sessionId ) || null ;
78+ }
79+
80+ async clearAllSessions ( ) : Promise < number > {
81+ await this . ensureLoaded ( ) ;
82+ const count = this . sessions . size ;
83+ this . sessions . clear ( ) ;
84+ await this . persist ( ) ;
85+ return count ;
86+ }
87+ }
0 commit comments