@unieai/rabi-client-ui-session 0.0.0-stage → 0.2.2-rc.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +7 -2
- package/lib/client.js +4 -0
- package/lib/index.js +6 -0
- package/lib/types/client/index.d.ts +210 -0
- package/lib/types/client/session-provider.d.ts +11 -0
- package/lib/types/index.d.ts +4 -0
- package/locale/de.json +6 -0
- package/locale/en.json +5 -0
- package/locale/es.json +6 -0
- package/locale/fr.json +6 -0
- package/locale/ja.json +6 -0
- package/locale/pt.json +6 -0
- package/locale/ru.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +47 -4
- package/src/client/index.ts +739 -0
- package/src/client/session-provider.tsx +19 -0
- package/src/index.ts +4 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DeepSeek
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @unieai/rabi-client-ui-session
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Session Controller adapter for React and session-scoped slots
|
|
4
|
+
|
|
5
|
+
Part of Rabi, the agent harness UnieAI Code runs on. Installed as a dependency of `@unieai/rabi`;
|
|
6
|
+
not meant to be used on its own.
|
|
7
|
+
|
|
8
|
+
See LICENSE for the license and copyright of this package.
|
package/lib/client.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
|
|
2
|
+
window.__ModuleLoader__.load({id:`@unieai/rabi-client-ui-session`,factory:require=>{var module={exports:{}};var exports=module.exports;Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let _unieai_cordis=require("@unieai/cordis");let _unieai_rabi_client_store=require("@unieai/rabi-client-store");let _unieai_rabi_client_ui_slots=require("@unieai/rabi-client-ui-slots");let react_jsx_runtime=require("react/jsx-runtime");const SIMPLE_ESCAPES={'"':`"`,"\\":`\\`,"/":`/`,b:`\b`,f:`\f`,n:`
|
|
3
|
+
`,r:`\r`,t:` `};const CONTENT_ESCAPE=/[\\\u0000-\u001f]/u;function isWhitespace(c){return c===` `||c===`
|
|
4
|
+
`||c===`\r`||c===` `}function isHex(c){return c>=`0`&&c<=`9`||c>=`a`&&c<=`f`||c>=`A`&&c<=`F`}var PartialArguments=class PartialArguments{static EMPTY=PartialArguments.fromObject({});static fromText(text){const view=new PartialArguments;view.append(text);view.sealed=true;return view}static fromObject(value){const view=new PartialArguments;view.object=typeof value===`object`&&value!==null&&!Array.isArray(value)?value:{};view.sealed=true;return view}chunks=[];object;sealed=false;#ends=[];#size=0;#consumed=0;#mode=`root`;#escape=false;#keyStart=0;#keyEscaped=false;#key=``;#current=null;#nestedEnds=[];#nestedInString=false;#invalidAt;#invalidValue=false;#entries=new Map;#order=[];#reads=new Map;get isSealed(){return this.sealed}get invalid(){this.scan();return this.#mode===`invalid`||this.#invalidValue}append(fragment){if(this.sealed)throw new Error(`PartialArguments: cannot append to a sealed view`);if(fragment.length===0)return;this.chunks.push(fragment);this.#size+=fragment.length;this.#ends.push(this.#size)}settle(text){if(this.object!==void 0||text.length!==this.#size)return PartialArguments.fromText(text);let offset=0;for(const chunk of this.chunks){if(!text.startsWith(chunk,offset))return PartialArguments.fromText(text);offset+=chunk.length}this.chunks=text.length===0?[]:[text];this.#ends=text.length===0?[]:[text.length];this.sealed=true;return this}refresh(){if(this.#reads.size===0)return false;this.scan();let changed=false;let completions=false;for(const read of this.#reads.values()){if(read.completion){completions=true;continue}changed=this.refreshRead(read)||changed}if(completions){for(const read of this.#reads.values())if(read.completion)changed=this.refreshRead(read)||changed}if(this.sealed)this.#reads.clear();return changed}refreshRead(read){const now=read.answer();if(Object.is(now,read.last))return false;read.last=now;return true}closed(){return this.remember(`closed`,``,()=>this.closedNow())}keys(){return this.remember(`keys`,``,()=>this.keysNow(),keys=>keys.length)}has(key){return this.remember(`has`,key,()=>this.hasNow(key))}complete(key){return this.remember(`complete`,key,()=>this.completeNow(key))}stringLength(key,options){const step=Math.max(1,Math.floor(options?.step??1));const offset=options?.offset??0;return this.remember(`length:${step}:${offset}`,key,()=>this.lengthNow(key),length=>length===void 0?void 0:Math.ceil((length+offset)/step))}stringExceeds(key,maxLength){const limit=Math.max(0,Math.floor(maxLength));return this.remember(`exceeds:${limit}`,key,()=>(this.lengthNow(key,limit+1)??0)>limit)}text(key){return this.remember(`text`,key,()=>this.textNow(key))}textPrefix(key,maxLength){const limit=Math.max(1,Math.floor(maxLength));return this.remember(`prefix:${limit}`,key,()=>this.textPrefixNow(key,limit))}value(key){return this.remember(`value`,key,()=>this.valueNow(key))}remember(kind,key,read,comparison){this.scan();const result=read();if(!this.sealed){const id=`${kind}/${key}`;if(!this.#reads.has(id))this.#reads.set(id,{completion:kind===`complete`,answer:comparison===void 0?read:()=>comparison(read()),last:comparison===void 0?result:comparison(result)})}return result}closedNow(){return this.sealed||this.#mode===`closed`||this.#mode===`invalid`}keysNow(){return this.object===void 0?this.#order:Object.keys(this.object)}hasNow(key){return this.object===void 0?this.#entries.has(key):Object.hasOwn(this.object,key)}completeNow(key){if(this.object!==void 0)return Object.hasOwn(this.object,key);const entry=this.#entries.get(key);return entry!==void 0&&entry.end>=0&&(entry.kind===`string`?entry.invalidAt===void 0:!entry.invalid)}lengthNow(key,limit=Number.POSITIVE_INFINITY){if(this.object!==void 0){const field=Object.hasOwn(this.object,key)?this.object[key]:void 0;return typeof field===`string`?field.length:void 0}const entry=this.#entries.get(key);if(entry?.kind!==`string`)return void 0;if(entry.text!==void 0&&entry.text.at===entry.end)return entry.text.length;const read=entry.length??={at:entry.start,length:0,text:``};this.readString(entry,read,limit,false);return read.length}textNow(key){if(this.object!==void 0){const field=Object.hasOwn(this.object,key)?this.object[key]:void 0;return typeof field===`string`?field:void 0}const entry=this.#entries.get(key);if(entry?.kind!==`string`)return void 0;if(entry.text===void 0&&entry.end>=0&&entry.needsDecoding&&entry.invalidAt===void 0){let text;try{text=JSON.parse(`"${this.slice(entry.start,entry.end)}"`)}catch(_error){}if(text!==void 0)entry.text={at:entry.end,length:text.length,text}}const read=entry.text??={at:entry.start,length:0,text:``};this.readString(entry,read,Number.POSITIVE_INFINITY,true);return read.text}textPrefixNow(key,maxLength){if(this.object!==void 0){const field=Object.hasOwn(this.object,key)?this.object[key]:void 0;return typeof field===`string`?field.slice(0,maxLength):void 0}const entry=this.#entries.get(key);if(entry?.kind!==`string`)return void 0;const prefixes=entry.prefixes??=new Map;let read=prefixes.get(maxLength);if(read===void 0){read={at:entry.start,length:0,text:``};prefixes.set(maxLength,read)}this.readString(entry,read,maxLength,true);return read.text}valueNow(key){if(this.object!==void 0){if(!Object.hasOwn(this.object,key))return void 0;const field=this.object[key];return typeof field===`string`?void 0:field}const entry=this.#entries.get(key);if(entry?.kind!==`value`||entry.end<0||entry.invalid)return void 0;if(entry.parsed===void 0)try{entry.parsed=JSON.parse(this.slice(entry.start,entry.end))}catch(_error){entry.invalid=true;this.#invalidValue=true}return entry.parsed}chunkAt(at){let low=0;let high=this.#ends.length;while(low<high){const mid=low+high>>>1;if(this.#ends[mid]<=at)low=mid+1;else high=mid}return low}slice(start,end){if(start>=end)return``;const first=this.chunkAt(start);const last=this.chunkAt(end-1);const base=first===0?0:this.#ends[first-1];if(first===last)return this.chunks[first].slice(start-base,end-base);const parts=[this.chunks[first].slice(start-base)];for(let i=first+1;i<last;i++)parts.push(this.chunks[i]);parts.push(this.chunks[last].slice(0,end-this.#ends[last-1]));return parts.join(``)}readString(entry,read,limit,materialize){const end=Math.min(entry.end<0?this.#consumed:entry.end,entry.invalidAt??Number.POSITIVE_INFINITY,this.#invalidAt??Number.POSITIVE_INFINITY);if(!entry.needsDecoding){const length=Math.min(end-read.at,limit-read.length);if(length<=0)return;if(materialize)read.text+=this.slice(read.at,read.at+length);read.at+=length;read.length+=length;return}let chunkIndex=this.chunkAt(read.at);while(read.at<end&&read.length<limit){const base=chunkIndex===0?0:this.#ends[chunkIndex-1];const chunk=this.chunks[chunkIndex];const remaining=chunk.slice(read.at-base,Math.min(chunk.length,end-base));const boundary=remaining.search(CONTENT_ESCAPE);const length=Math.min(boundary<0?remaining.length:boundary,limit-read.length);if(length>0){if(materialize)read.text+=remaining.slice(0,length);read.at+=length;read.length+=length;if(read.at===base+chunk.length)chunkIndex++;continue}const type=remaining.length>1?remaining[1]:read.at+1<end?this.chunks[chunkIndex+1][0]:void 0;let decoded;let width=2;if(remaining[0]===`\\`&&type===void 0&&entry.end<0)return;if(remaining[0]===`\\`&&type===`u`){const hex=this.slice(read.at+2,Math.min(end,read.at+6));let valid=true;for(let i=0;i<hex.length;i++)if(!isHex(hex[i]))valid=false;if(valid){if(hex.length<4&&entry.end<0)return;if(hex.length===4)decoded=String.fromCharCode(Number.parseInt(hex,16))}width=6}else if(remaining[0]===`\\`&&type!==void 0)decoded=SIMPLE_ESCAPES[type];if(decoded===void 0){entry.invalidAt=read.at;this.#invalidValue=true;return}if(materialize)read.text+=decoded;read.length++;read.at+=width;while(chunkIndex<this.chunks.length&&read.at>=this.#ends[chunkIndex])chunkIndex++}}scan(){if(this.object!==void 0||this.#consumed===this.#size)return;for(let i=this.chunkAt(this.#consumed);i<this.chunks.length&&this.#invalidAt===void 0;i++){const pending=this.chunks[i];const base=i===0?0:this.#ends[i-1];for(let index=this.#consumed-base;index<pending.length&&this.#mode!==`invalid`;index++){if(this.#mode===`string`||this.#mode===`nested`&&this.#nestedInString){const end=this.stringBoundary(pending,index);this.#consumed+=end-index;index=end;if(index===pending.length)break}this.step(pending[index],this.#consumed);this.#consumed++}}}stringBoundary(fragment,start){let at=start;while(true){const quote=fragment.indexOf(`"`,at);const end=quote<0?fragment.length:quote;if(this.#mode===`string`){const entry=this.#current;if(!entry.needsDecoding&&CONTENT_ESCAPE.test(fragment.slice(at,end)))entry.needsDecoding=true}let slashStart=end;while(slashStart>at&&fragment[slashStart-1]===`\\`)slashStart--;const escaped=(end-slashStart)%2===1!==(slashStart===at&&this.#escape);this.#escape=quote<0&&escaped;if(quote<0||!escaped)return end;at=quote+1}}step(c,at){switch(this.#mode){case`root`:if(isWhitespace(c))return;if(c===`{`){this.#mode=`key-or-end`;return}this.fail();return;case`key-or-end`:if(isWhitespace(c))return;if(c===`}`){this.#mode=`closed`;return}if(c===`"`){this.beginKey(at);return}this.fail();return;case`key-only`:if(isWhitespace(c))return;if(c===`"`){this.beginKey(at);return}this.fail();return;case`key`:this.stepKey(c,at);return;case`colon`:if(isWhitespace(c))return;if(c===`:`){this.#mode=`value`;return}this.fail();return;case`value`:this.beginValue(c,at);return;case`string`:{const entry=this.#current;entry.end=at;this.#current=null;this.#mode=`comma-or-end`;return}case`scalar`:this.stepScalar(c,at);return;case`nested`:this.stepNested(c,at);return;case`comma-or-end`:if(isWhitespace(c))return;if(c===`,`){this.#mode=`key-only`;return}if(c===`}`){this.#mode=`closed`;return}this.fail();return;case`closed`:if(isWhitespace(c))return;this.fail();return;case`invalid`:return;default:assertNever(this.#mode)}}fail(){this.#invalidAt=this.#consumed;this.#mode=`invalid`;this.#current=null}beginKey(at){this.#mode=`key`;this.#keyStart=at+1;this.#keyEscaped=false;this.#escape=false}stepKey(c,at){if(c<` `){this.fail();return}if(this.#escape){this.#escape=false;return}if(c===`\\`){this.#escape=true;this.#keyEscaped=true;return}if(c!==`"`)return;const raw=this.slice(this.#keyStart,at);if(this.#keyEscaped)try{this.#key=JSON.parse(`"${raw}"`)}catch(_error){this.fail();return}else this.#key=raw;this.#mode=`colon`}open(entry){if(!this.#entries.has(this.#key))this.#order.push(this.#key);this.#entries.set(this.#key,entry);this.#current=entry}beginValue(c,at){if(isWhitespace(c))return;if(c===`"`){this.open({kind:`string`,start:at+1,end:-1,needsDecoding:false,invalidAt:void 0,length:void 0,text:void 0,prefixes:void 0});this.#escape=false;this.#mode=`string`;return}if(c===`}`||c===`,`||c===`:`||c===`]`){this.fail();return}this.open({kind:`value`,start:at,end:-1,parsed:void 0,invalid:false});if(c===`{`||c===`[`){this.#mode=`nested`;this.#nestedEnds=[c===`{`?`}`:`]`];this.#nestedInString=false;this.#escape=false;return}this.#mode=`scalar`}stepScalar(c,at){if(c!==`,`&&c!==`}`&&!isWhitespace(c))return;this.closeValue(at);this.#mode=c===`,`?`key-only`:c===`}`?`closed`:`comma-or-end`}stepNested(c,at){if(this.#nestedInString){this.#nestedInString=false;return}if(c===`"`){this.#nestedInString=true;return}if(c===`{`||c===`[`){this.#nestedEnds.push(c===`{`?`}`:`]`);return}if(c===`}`||c===`]`){if(this.#nestedEnds.pop()!==c){this.fail();return}if(this.#nestedEnds.length===0){this.closeValue(at+1);this.#mode=`comma-or-end`}}}closeValue(end){const entry=this.#current;entry.end=end;this.#current=null}};function assertNever(value,context){const rendered=JSON.stringify(value)??String(value);throw new Error(`unreachable variant${context?` in ${context}`:``}: ${rendered}`)}var WeakMapWithValues=class{keys=new WeakMap;valueSet=new Set;values=this.valueSet;get(key){return this.keys.get(key)}has(key){return this.keys.has(key)}set(key,value){if(this.keys.has(key)){const previous=this.keys.get(key);if(previous===value)return this;this.valueSet.delete(previous)}this.keys.set(key,value);this.valueSet.add(value);return this}delete(key){if(!this.keys.has(key))return false;const value=this.keys.get(key);const deleted=this.keys.delete(key);this.valueSet.delete(value);return deleted}clear(){this.keys=new WeakMap;this.valueSet.clear()}};function renderSessionArea(binding,{empty,children}){if(binding.key===void 0)return(0,react_jsx_runtime.jsx)(react_jsx_runtime.Fragment,{children:empty?.()??null});return(0,react_jsx_runtime.jsx)(react_jsx_runtime.Fragment,{children})}var PendingInteractionDomain=class{precedence;changed;values=new Map;constructor(precedence,changed){this.precedence=precedence;this.changed=changed}valuesSnapshot(){return[...this.values.values()].map(entry=>entry.interaction)}publish(interaction,delegate){if(this.values.has(interaction.key))throw new Error(`ui-session: duplicate pending interaction key '${interaction.key}'`);this.values.set(interaction.key,{interaction,delegate});this.changed();let active=true;return()=>{if(!active)return;active=false;if(!this.values.delete(interaction.key))return;this.changed()}}release(){const delegates=[...this.values.values()].map(entry=>entry.delegate);this.values.clear();return delegates}};const BUILTIN_SOURCE={hooks:[`session`],keyedHooks:[`projection`],props:[`sessionId`],resolve:binding=>({hooks:{session:binding.session},keyedHooks:{projection:key=>binding.session.projections.faceOf(key)},props:{sessionId:binding.sessionId}})};var UiSession=class extends _unieai_cordis.Service{sessions;descriptors=[BUILTIN_SOURCE];bindings=new WeakMapWithValues;absent;current;pendingDomains=[];pendingSnapshot=new Map;running=new Map;completionUnread=new Set;statusSnapshot=new Map;statusListeners=new Set;mainRetainId;disposeMainRetain=()=>{};active=true;sessionStatus={getSnapshot:()=>this.statusSnapshot,subscribe:listener=>{this.statusListeners.add(listener);return()=>{this.statusListeners.delete(listener)}}};adapter;constructor(ctx,sessions){super(ctx,`uiSession`);this.sessions=sessions;this.absent=createBindingSource(this.materializeAbsent());this.current=createBindingSource(this.absent.value);this.adapter={current:this.current,bindingSource:target=>this.bindingSource(target),renderArea:renderSessionArea};ctx.effect(()=>{const disposeList=sessions.list.subscribe(()=>{this.publishMain()});const disposeStatus=sessions.list.subscribe(()=>{this.reconcileStatus()});const disposeRemoteStatus=ctx.remote.$on(`api-session/status`,(sessionId,running)=>{this.observeRunning(sessionId,running)});this.publishMain();this.reconcileStatus();return()=>{this.active=false;disposeList();disposeStatus();disposeRemoteStatus();this.disposeMainRetain();const records=[...this.bindings.values];this.bindings.clear();for(const record of records)record.release()}},`ui-session: Session binding projection`)}bindingSource(reference){if(!this.active)return this.absent;if(reference===void 0)return this.absent;const owner=reference.binding;if(this.sessions.binding(reference.sessionId)!==owner)throw new Error(`ui-session: Session reference is not active in this Controller`);return this.sourceFor(owner)}whenAccess(sessionId,action,callback){const access=this.ctx.get(`remoteAccess`);if(access===void 0)throw new Error(`ui-session: whenAccess requires the remoteAccess service`);return access.whenResourceAccess(`session`,sessionId,action,callback)}provide(descriptor){const runtimeDescriptor=descriptor;const dispose=this.ctx.effect(()=>{this.descriptors.push(runtimeDescriptor);try{this.rebuildBindings()}catch(error){this.descriptors.pop();throw error}return()=>{const index=this.descriptors.indexOf(runtimeDescriptor);this.descriptors.splice(index,1);this.rebuildBindings()}},`uiSession.provide()`);return()=>{dispose()}}registerPendingInteraction(precedence){const domain=new PendingInteractionDomain(precedence,()=>{this.publishPendingInteractions()});const runtimeDomain=domain;this.ctx.effect(()=>{this.pendingDomains.push(runtimeDomain);this.publishPendingInteractions();return async()=>{const delegates=domain.release();const index=this.pendingDomains.indexOf(runtimeDomain);this.pendingDomains.splice(index,1);this.publishPendingInteractions();await Promise.allSettled(delegates.map(delegate=>Promise.resolve().then(delegate)))}},`uiSession.registerPendingInteraction()`);return(interaction,delegate)=>domain.publish(interaction,delegate)}rebuildBindings(){const absent=this.materializeAbsent();const updates=[...this.bindings.values].map(record=>({source:record.source,value:this.materialize(record.owner)}));this.absent.value=absent;for(const{source,value}of updates)source.value=value;(0,_unieai_rabi_client_store.notifySubscribers)(this.absent.listeners,`[ui-session] absent binding`);for(const{source}of updates)(0,_unieai_rabi_client_store.notifySubscribers)(source.listeners,`[ui-session] Session binding`);this.publishMain()}sourceFor(owner){const cached=this.bindings.get(owner);if(cached!==void 0)return cached.source;const record=this.createMaterializedBinding(owner);this.bindings.set(owner,record);return record.source}publishMain(){if(!this.active)return;const byId=this.sessions.list.getSnapshot().byId;const currentId=this.current.value.key;const nextId=currentId!==void 0&&(this.sessions.retainInfo(currentId).getSnapshot().retainedBy.mainView??0)>0?currentId:Object.values(byId).find(candidate=>(candidate.retainedBy.mainView??0)>0)?.id;this.watchMainRetention(nextId);const owner=nextId===void 0?void 0:this.sessions.binding(nextId);const value=owner===void 0?this.absent.value:this.sourceFor(owner).value;if(this.current.value===value)return;this.current.value=value;(0,_unieai_rabi_client_store.notifySubscribers)(this.current.listeners,`[ui-session] main binding`)}watchMainRetention(sessionId){if(sessionId===this.mainRetainId)return;this.disposeMainRetain();this.mainRetainId=sessionId;this.disposeMainRetain=sessionId===void 0?()=>{}:this.sessions.retainInfo(sessionId).subscribe(()=>{this.publishMain()})}publishPendingInteractions(){const next=new Map;for(const domain of this.pendingDomains)for(const interaction of domain.valuesSnapshot()){const precedence=domain.precedence(interaction);const previous=next.get(interaction.sessionId);if(previous===void 0||precedence>=previous.precedence)next.set(interaction.sessionId,{interaction,precedence})}const projected=new Map([...next].map(([sessionId,value])=>[sessionId,value.interaction]));if(samePendingInteractions(this.pendingSnapshot,projected))return;this.pendingSnapshot=projected;this.publishStatus()}observeRunning(sessionId,running){const previous=this.running.get(sessionId);const beforeBaseline=this.sessions.list.getSnapshot().phase===`pending`;this.running.set(sessionId,running);if(running)this.completionUnread.delete(sessionId);else if((previous===true||previous===void 0&&beforeBaseline)&&!this.isMain(sessionId))this.completionUnread.add(sessionId);this.publishStatus()}reconcileStatus(){const list=this.sessions.list.getSnapshot();const present=new Set(Object.keys(list.byId));for(const id of list.ids){const row=list.byId[id];const previous=this.running.get(id);if(previous===void 0)this.running.set(id,row.running);else if(previous!==row.running)this.observeRunning(id,row.running)}for(const id of present)if(this.isMain(id))this.completionUnread.delete(id);if(list.phase===`ready`)for(const id of this.running.keys()){if(present.has(id))continue;this.running.delete(id);this.completionUnread.delete(id)}this.publishStatus()}isMain(sessionId){return(this.sessions.list.getSnapshot().byId[sessionId]?.retainedBy.mainView??0)>0}publishStatus(){const ids=new Set([...Object.keys(this.sessions.list.getSnapshot().byId),...this.running.keys(),...this.pendingSnapshot.keys(),...this.completionUnread]);const next=new Map;for(const id of ids)next.set(id,{running:this.running.get(id),pendingInteraction:this.pendingSnapshot.get(id),completionUnread:this.completionUnread.has(id)});if(sameSessionStatus(this.statusSnapshot,next))return;this.statusSnapshot=next;(0,_unieai_rabi_client_store.notifySubscribers)(this.statusListeners,`[ui-session] Session status`)}createMaterializedBinding(owner){const value=this.materialize(owner);this.ctx.slots.bindStoreScope(value);const source=createBindingSource(value);const releaseEffect=owner.ctx.effect(()=>()=>{if(this.bindings.get(owner)===record)this.bindings.delete(owner);source.value=this.absent.value;(0,_unieai_rabi_client_store.notifySubscribers)(source.listeners,`[ui-session] Session binding`);this.publishMain()},`ui-session: binding ${owner.sessionId}`);const record={owner,source,release:()=>{releaseEffect()}};return record}materialize(binding){const hooks={};const keyedHooks={};const props={};const finalProps=new Set;for(const descriptor of this.descriptors){const contribution=descriptor.resolve(binding);validateContribution(descriptor,contribution);copyDeclared(`hook`,hooks,descriptor.hooks,contribution.hooks,finalProps);copyDeclared(`keyed hook`,keyedHooks,descriptor.keyedHooks,contribution.keyedHooks,finalProps);copyDeclared(`prop`,props,descriptor.props,contribution.props,finalProps)}return{key:binding.sessionId,ctx:binding.ctx,hooks,keyedHooks,props}}materializeAbsent(){const hooks={};const keyedHooks={};const props={};const finalProps=new Set;for(const descriptor of this.descriptors){declareAbsent(`hook`,hooks,descriptor.hooks,finalProps);declareAbsent(`keyed hook`,keyedHooks,descriptor.keyedHooks,finalProps);declareAbsent(`prop`,props,descriptor.props,finalProps)}return{key:void 0,hooks,keyedHooks,props}}};function createBindingSource(value){const source={value,listeners:new Set,getSnapshot:()=>source.value,subscribe:listener=>{source.listeners.add(listener);return()=>{source.listeners.delete(listener)}}};return source}function validateContribution(descriptor,contribution){rejectUndeclared(`hook`,descriptor.hooks,contribution.hooks);rejectUndeclared(`keyed hook`,descriptor.keyedHooks,contribution.keyedHooks);rejectUndeclared(`prop`,descriptor.props,contribution.props)}function rejectUndeclared(kind,declared,values){for(const name of Object.keys(values??{}))if(!(declared??[]).includes(name))throw new Error(`uiSession.provide: undeclared ${kind} '${name}'`)}function copyDeclared(kind,target,declared,values,finalProps){for(const name of declared??[]){claimStandardProp(kind,name,finalProps);const value=values?.[name];if(value===void 0)throw new Error(`uiSession.provide: missing ${kind} '${name}'`);target[name]=value}}function declareAbsent(kind,target,declared,finalProps){for(const name of declared??[]){claimStandardProp(kind,name,finalProps);target[name]=void 0}}function claimStandardProp(kind,name,finalProps){const propName=kind===`prop`?name:(0,_unieai_rabi_client_ui_slots.standardHookPropName)(name);if(finalProps.has(propName))throw new Error(`uiSession.provide: duplicate ${kind} '${name}' at prop '${propName}'`);finalProps.add(propName)}const inject=[`sessions`,`slots`,`remote`,`remoteAccess`];function apply(ctx){const service=new UiSession(ctx,ctx.sessions);ctx.slots.provideRoot({hooks:{sessions:ctx.sessions.list,sessionStatus:service.sessionStatus},keyedHooks:{sessionRetainInfo:key=>ctx.sessions.retainInfo(key),sessionAccess:(sessionId,action)=>action===void 0?void 0:ctx.remoteAccess.source(`session`,sessionId,action)}});ctx.slots.installScope(`session`,service.adapter);service.provide({keyedHooks:[`access`],resolve:binding=>({keyedHooks:{access:action=>ctx.remoteAccess.source(`session`,binding.sessionId,action)}})})}function sameSessionStatus(left,right){if(left.size!==right.size)return false;for(const[id,status]of left){const candidate=right.get(id);if(candidate===void 0||candidate.running!==status.running||candidate.pendingInteraction!==status.pendingInteraction||candidate.completionUnread!==status.completionUnread)return false}return true}function samePendingInteractions(left,right){if(left.size!==right.size)return false;for(const[sessionId,interaction]of left)if(right.get(sessionId)!==interaction)return false;return true}exports.UiSession=UiSession;exports.apply=apply;exports.inject=inject;return module.exports}});
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/** Session Controller adapter for React selector hooks and Slot scope data. */
|
|
2
|
+
import { Service, type Context } from '@unieai/cordis';
|
|
3
|
+
import type { ISessions, SessionBinding, SessionListState, SessionReference, SessionRetainInfo, SessionSnapshot, UseProjection } from '@unieai/rabi-api-session-controller/client';
|
|
4
|
+
import type { SessionId } from '@unieai/rabi-session/types';
|
|
5
|
+
import type { AccessEffect, RemoteEndpoint } from '@unieai/rabi-api-remote-access/client';
|
|
6
|
+
import type { HostObservable, KeyedStandardSource, MaybeSnapshotSelectorHook, SlotScopeAdapter, SnapshotSelectorHook, StandardSourceBinding } from '@unieai/rabi-client-ui-slots';
|
|
7
|
+
/** Selector hook over the Session Controller list and current selection. */
|
|
8
|
+
export type UseSessions = SnapshotSelectorHook<SessionListState>;
|
|
9
|
+
/** Selector hook over one Session's lifecycle and control state. */
|
|
10
|
+
export type SessionSnapshotSelector = SnapshotSelectorHook<SessionSnapshot>;
|
|
11
|
+
/** Public name for the Session lifecycle selector hook. */
|
|
12
|
+
export type UseSession = SessionSnapshotSelector;
|
|
13
|
+
/** Common identity carried by every Session-scoped pending interaction. */
|
|
14
|
+
export interface SessionPendingInteractionBase {
|
|
15
|
+
/** Opaque request identity; a replacement request must use a new key. */
|
|
16
|
+
readonly key: string;
|
|
17
|
+
/** Domain-owned presentation discriminator. */
|
|
18
|
+
readonly kind: string;
|
|
19
|
+
/** Session whose UI can answer this interaction. */
|
|
20
|
+
readonly sessionId: SessionId;
|
|
21
|
+
}
|
|
22
|
+
/** Declaration-merged map of domain keys to their pending-interaction values. */
|
|
23
|
+
export interface SessionPendingInteractionMap {
|
|
24
|
+
}
|
|
25
|
+
/** Union of every pending-interaction value contributed by the assembled Client. */
|
|
26
|
+
export type SessionPendingInteraction = [
|
|
27
|
+
keyof SessionPendingInteractionMap
|
|
28
|
+
] extends [never] ? SessionPendingInteractionBase : SessionPendingInteractionMap[keyof SessionPendingInteractionMap];
|
|
29
|
+
/** Independent UI status facts for one Session identity. */
|
|
30
|
+
export interface SessionStatus {
|
|
31
|
+
/** Latest known running state; absent until a baseline or event establishes it. */
|
|
32
|
+
readonly running: boolean | undefined;
|
|
33
|
+
/** Highest-precedence domain request currently awaiting user interaction. */
|
|
34
|
+
readonly pendingInteraction: SessionPendingInteraction | undefined;
|
|
35
|
+
/** Whether an observed stop outside the main view still needs acknowledgement. */
|
|
36
|
+
readonly completionUnread: boolean;
|
|
37
|
+
}
|
|
38
|
+
/** Current UI status indexed by Session identity. */
|
|
39
|
+
export type SessionStatusSnapshot = ReadonlyMap<SessionId, SessionStatus>;
|
|
40
|
+
/** Selector hook over the unified Session UI status snapshot. */
|
|
41
|
+
export type UseSessionStatus = SnapshotSelectorHook<SessionStatusSnapshot>;
|
|
42
|
+
/** Selector hook for explicit or surrounding-Provider Session reference counts. */
|
|
43
|
+
export interface UseSessionRetainInfo {
|
|
44
|
+
/**
|
|
45
|
+
* Read the complete retain information for an explicit Session identity.
|
|
46
|
+
* @param sessionId - Session identity to inspect without retaining it.
|
|
47
|
+
* @returns current local reference counts, or absence while the source is unavailable.
|
|
48
|
+
*/
|
|
49
|
+
(sessionId: SessionId): SessionRetainInfo | undefined;
|
|
50
|
+
/**
|
|
51
|
+
* Select from the retain information for an explicit Session identity.
|
|
52
|
+
* @param sessionId - Session identity to inspect without retaining it.
|
|
53
|
+
* @param selector - projection over the current value.
|
|
54
|
+
* @param equal - optional selected-value equality.
|
|
55
|
+
* @returns selected value.
|
|
56
|
+
*/
|
|
57
|
+
<Selected>(sessionId: SessionId, selector: (value: SessionRetainInfo | undefined) => Selected, equal?: (left: Selected, right: Selected) => boolean): Selected;
|
|
58
|
+
/**
|
|
59
|
+
* Select from the surrounding Provider's Session retain information.
|
|
60
|
+
* @param selector - projection receiving absence outside a Session binding.
|
|
61
|
+
* @param equal - optional selected-value equality.
|
|
62
|
+
* @returns selected value.
|
|
63
|
+
*/
|
|
64
|
+
<Selected>(selector: (value: SessionRetainInfo | undefined) => Selected, equal?: (left: Selected, right: Selected) => boolean): Selected;
|
|
65
|
+
}
|
|
66
|
+
/** Publish one pending interaction and define how plugin teardown delegates it. */
|
|
67
|
+
export type PendingInteractionPublisher<T extends SessionPendingInteractionBase> = (interaction: T, delegate: () => Promise<void>) => () => void;
|
|
68
|
+
declare module '@unieai/rabi-client-ui-slots' {
|
|
69
|
+
interface SlotScopeTargetMap {
|
|
70
|
+
session: SessionReference;
|
|
71
|
+
}
|
|
72
|
+
interface GlobalStandardProps {
|
|
73
|
+
/** Session list and current selection. */
|
|
74
|
+
useSessions: UseSessions;
|
|
75
|
+
useSessionStatus: UseSessionStatus;
|
|
76
|
+
useSessionRetainInfo: UseSessionRetainInfo;
|
|
77
|
+
/** Whether the current Peer may call `action` on one Session resource. */
|
|
78
|
+
useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean;
|
|
79
|
+
}
|
|
80
|
+
interface SessionStandardProps {
|
|
81
|
+
/** Current Session lifecycle and control state. */
|
|
82
|
+
useSession: SessionSnapshotSelector;
|
|
83
|
+
/** Current Session identity. */
|
|
84
|
+
sessionId: SessionId;
|
|
85
|
+
/** Host-computed projection values addressed by projection key. */
|
|
86
|
+
useProjection: UseProjection;
|
|
87
|
+
/** Whether the current Peer may call `action` on this Session resource. */
|
|
88
|
+
useAccess: (action: RemoteEndpoint) => boolean;
|
|
89
|
+
}
|
|
90
|
+
interface SessionMaybeStandardProps {
|
|
91
|
+
/** Current Session state, absent while no Session is selected. */
|
|
92
|
+
useSession: MaybeSnapshotSelectorHook<SessionSnapshot>;
|
|
93
|
+
/** Current Session identity, absent while no Session is selected. */
|
|
94
|
+
sessionId: SessionId | undefined;
|
|
95
|
+
/** Host-computed projection values; every key is absent without a Session. */
|
|
96
|
+
useProjection: UseProjection;
|
|
97
|
+
/** The bound Session's access answer; `undefined` without a Session, which callers treat as not allowed. */
|
|
98
|
+
useAccess: (action: RemoteEndpoint) => boolean | undefined;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
declare module '@unieai/rabi-api-session-controller/client' {
|
|
102
|
+
interface SessionReferenceSourceMap {
|
|
103
|
+
mainView: unknown;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
declare module '@unieai/cordis' {
|
|
107
|
+
interface Context {
|
|
108
|
+
/** Session Controller adapter and session-scoped source registry. */
|
|
109
|
+
uiSession: UiSession;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
type SessionSourceRoster = readonly string[] | undefined;
|
|
113
|
+
type SessionSourceRecord<Roster extends SessionSourceRoster, Value> = Roster extends readonly string[] ? Readonly<Record<Roster[number], Value>> : never;
|
|
114
|
+
/** Bare values produced by one Session-scoped source contribution. */
|
|
115
|
+
export interface SessionSourceContribution<Hooks extends SessionSourceRoster = SessionSourceRoster, KeyedHooks extends SessionSourceRoster = SessionSourceRoster, Props extends SessionSourceRoster = SessionSourceRoster> {
|
|
116
|
+
readonly hooks?: SessionSourceRecord<Hooks, HostObservable<unknown>>;
|
|
117
|
+
readonly keyedHooks?: SessionSourceRecord<KeyedHooks, KeyedStandardSource>;
|
|
118
|
+
readonly props?: SessionSourceRecord<Props, unknown>;
|
|
119
|
+
}
|
|
120
|
+
/** Static roster and per-Session resolver for one standard-props contribution. */
|
|
121
|
+
export interface SessionSourceDescriptor<Hooks extends SessionSourceRoster = SessionSourceRoster, KeyedHooks extends SessionSourceRoster = SessionSourceRoster, Props extends SessionSourceRoster = SessionSourceRoster> {
|
|
122
|
+
readonly hooks?: Hooks;
|
|
123
|
+
readonly keyedHooks?: KeyedHooks;
|
|
124
|
+
readonly props?: Props;
|
|
125
|
+
/**
|
|
126
|
+
* Resolve every declared member for one Session binding.
|
|
127
|
+
* @param binding - Controller-owned Session binding.
|
|
128
|
+
* @returns all declared bare sources and stable props.
|
|
129
|
+
*/
|
|
130
|
+
resolve(binding: SessionBinding): SessionSourceContribution<NoInfer<Hooks>, NoInfer<KeyedHooks>, NoInfer<Props>>;
|
|
131
|
+
}
|
|
132
|
+
/** Session-scoped source roster and renderer adapter. */
|
|
133
|
+
export declare class UiSession extends Service {
|
|
134
|
+
private readonly sessions;
|
|
135
|
+
private readonly descriptors;
|
|
136
|
+
private readonly bindings;
|
|
137
|
+
private readonly absent;
|
|
138
|
+
private readonly current;
|
|
139
|
+
private readonly pendingDomains;
|
|
140
|
+
private pendingSnapshot;
|
|
141
|
+
private readonly running;
|
|
142
|
+
private readonly completionUnread;
|
|
143
|
+
private statusSnapshot;
|
|
144
|
+
private readonly statusListeners;
|
|
145
|
+
private mainRetainId;
|
|
146
|
+
private disposeMainRetain;
|
|
147
|
+
private active;
|
|
148
|
+
/** Root source combining running, pending-interaction, and completion-reminder facts. */
|
|
149
|
+
readonly sessionStatus: HostObservable<SessionStatusSnapshot>;
|
|
150
|
+
/** Renderer-facing adapter for `session` and `session-maybe` scopes. */
|
|
151
|
+
readonly adapter: SlotScopeAdapter;
|
|
152
|
+
/**
|
|
153
|
+
* @param ctx - Client root context.
|
|
154
|
+
* @param sessions - Controller-owned Session object layer.
|
|
155
|
+
*/
|
|
156
|
+
constructor(ctx: Context, sessions: ISessions);
|
|
157
|
+
/**
|
|
158
|
+
* Resolve a stable renderer source for an owned Session reference or explicit absence.
|
|
159
|
+
* @param reference - active reference supplied by the Provider owner, or absence.
|
|
160
|
+
* @returns the binding source, which falls back to the absent projection when its generation ends.
|
|
161
|
+
* @throws when the reference does not belong to the active Controller generation.
|
|
162
|
+
*/
|
|
163
|
+
bindingSource(reference: SessionReference | undefined): HostObservable<StandardSourceBinding>;
|
|
164
|
+
/**
|
|
165
|
+
* Keep `callback`'s effects installed while the current Peer may call
|
|
166
|
+
* `action` on one Session resource, with the semantics of
|
|
167
|
+
* `ctx.remoteAccess.whenAccess`: `useSessionAccess` answers the same
|
|
168
|
+
* question during render.
|
|
169
|
+
* @param sessionId - the Session resource the guarded effects depend on.
|
|
170
|
+
* @param action - endpoint action the guarded effects depend on.
|
|
171
|
+
* @param callback - creates one disposer or an iterable of disposers.
|
|
172
|
+
* @returns idempotent disposer owned by the caller's Cordis fiber.
|
|
173
|
+
*/
|
|
174
|
+
whenAccess(sessionId: SessionId, action: RemoteEndpoint, callback: () => AccessEffect): () => void;
|
|
175
|
+
/**
|
|
176
|
+
* Register one Session-scoped standard-source contribution.
|
|
177
|
+
* @param descriptor - static member roster and per-binding resolver.
|
|
178
|
+
* @returns disposer owned by the caller's Cordis fiber.
|
|
179
|
+
*/
|
|
180
|
+
provide<const Hooks extends SessionSourceRoster = undefined, const KeyedHooks extends SessionSourceRoster = undefined, const Props extends SessionSourceRoster = undefined>(descriptor: SessionSourceDescriptor<Hooks, KeyedHooks, Props>): () => void;
|
|
181
|
+
/**
|
|
182
|
+
* Register one pending-interaction domain and return its publication function.
|
|
183
|
+
* Domain teardown first removes its visible values, then delegates and awaits
|
|
184
|
+
* every still-active owner request.
|
|
185
|
+
* @param precedence - deterministic cross-domain precedence; larger values win.
|
|
186
|
+
* @returns a function that publishes one interaction and its teardown delegation.
|
|
187
|
+
*/
|
|
188
|
+
registerPendingInteraction<T extends SessionPendingInteractionBase>(precedence: (interaction: T) => number): PendingInteractionPublisher<T>;
|
|
189
|
+
private rebuildBindings;
|
|
190
|
+
private sourceFor;
|
|
191
|
+
private publishMain;
|
|
192
|
+
private watchMainRetention;
|
|
193
|
+
private publishPendingInteractions;
|
|
194
|
+
private observeRunning;
|
|
195
|
+
private reconcileStatus;
|
|
196
|
+
private isMain;
|
|
197
|
+
private publishStatus;
|
|
198
|
+
private createMaterializedBinding;
|
|
199
|
+
private materialize;
|
|
200
|
+
private materializeAbsent;
|
|
201
|
+
}
|
|
202
|
+
/** Required Controller, renderer, Remote, and access services. */
|
|
203
|
+
export declare const inject: string[];
|
|
204
|
+
/**
|
|
205
|
+
* Install the Session root source and scoped adapter.
|
|
206
|
+
* @param ctx - Client Cordis context.
|
|
207
|
+
*/
|
|
208
|
+
export declare function apply(ctx: Context): void;
|
|
209
|
+
export {};
|
|
210
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Session-owned rendering semantics for the standard SessionProvider seat. */
|
|
2
|
+
import type { ReactNode } from 'react';
|
|
3
|
+
import type { SessionAreaProps, StandardSourceBinding } from '@unieai/rabi-client-ui-slots';
|
|
4
|
+
/**
|
|
5
|
+
* Render the selected Session body or its empty branch.
|
|
6
|
+
* @param binding - current Session scope binding.
|
|
7
|
+
* @param props - standard Session area render props.
|
|
8
|
+
* @returns the selected Session subtree.
|
|
9
|
+
*/
|
|
10
|
+
export declare function renderSessionArea(binding: StandardSourceBinding, { empty, children }: SessionAreaProps): ReactNode;
|
|
11
|
+
//# sourceMappingURL=session-provider.d.ts.map
|
package/locale/de.json
ADDED
package/locale/en.json
ADDED
package/locale/es.json
ADDED
package/locale/fr.json
ADDED
package/locale/ja.json
ADDED
package/locale/pt.json
ADDED
package/locale/ru.json
ADDED
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@unieai/rabi-client-ui-session",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"description": "Session Controller adapter for React and session-scoped slots",
|
|
4
|
+
"version": "0.2.2-rc.5",
|
|
5
|
+
"publishConfig": {
|
|
6
|
+
"access": "public"
|
|
7
|
+
},
|
|
8
|
+
"type": "module",
|
|
9
|
+
"main": "lib/index.js",
|
|
10
|
+
"types": "lib/types/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./lib/types/index.d.ts",
|
|
14
|
+
"default": "./lib/index.js"
|
|
15
|
+
},
|
|
16
|
+
"./client": {
|
|
17
|
+
"types": "./lib/types/client/index.d.ts",
|
|
18
|
+
"default": "./lib/client.js"
|
|
19
|
+
},
|
|
20
|
+
"./src/*": "./src/*",
|
|
21
|
+
"./package.json": "./package.json",
|
|
22
|
+
"./locale/*.json": "./locale/*.json"
|
|
23
|
+
},
|
|
24
|
+
"rabi": {
|
|
25
|
+
"client": {
|
|
26
|
+
"inject": [
|
|
27
|
+
"@unieai/rabi-api-remote-access",
|
|
28
|
+
"@unieai/rabi-api-remotes",
|
|
29
|
+
"@unieai/rabi-api-session-controller",
|
|
30
|
+
"@unieai/rabi-client-ui-renderer"
|
|
31
|
+
],
|
|
32
|
+
"platform": "web"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"license": "MIT",
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"@unieai/cordis": "4.1.0"
|
|
38
|
+
},
|
|
39
|
+
"files": [
|
|
40
|
+
"locale/*.json",
|
|
41
|
+
"lib/index.js",
|
|
42
|
+
"lib/client.js",
|
|
43
|
+
"lib/types/**/*.d.ts",
|
|
44
|
+
"lib/types/**/*.d.ts.map",
|
|
45
|
+
"lib/**/*.js.map",
|
|
46
|
+
"src",
|
|
47
|
+
"README.md"
|
|
48
|
+
]
|
|
49
|
+
}
|
|
@@ -0,0 +1,739 @@
|
|
|
1
|
+
/** Session Controller adapter for React selector hooks and Slot scope data. */
|
|
2
|
+
import { Service, type Context } from '@unieai/cordis'
|
|
3
|
+
import type {
|
|
4
|
+
ISessions,
|
|
5
|
+
SessionBinding,
|
|
6
|
+
SessionListState,
|
|
7
|
+
SessionReference,
|
|
8
|
+
SessionRetainInfo,
|
|
9
|
+
SessionSnapshot,
|
|
10
|
+
SessionSummary,
|
|
11
|
+
UseProjection,
|
|
12
|
+
} from '@unieai/rabi-api-session-controller/client'
|
|
13
|
+
import type { SessionId } from '@unieai/rabi-session/types'
|
|
14
|
+
import type {} from '@unieai/rabi-api-remotes/client'
|
|
15
|
+
import type { AccessEffect, RemoteEndpoint } from '@unieai/rabi-api-remote-access/client'
|
|
16
|
+
import { notifySubscribers } from '@unieai/rabi-client-store'
|
|
17
|
+
import { WeakMapWithValues } from '@unieai/rabi-util-values'
|
|
18
|
+
import { standardHookPropName } from '@unieai/rabi-client-ui-slots'
|
|
19
|
+
import type {
|
|
20
|
+
HostObservable,
|
|
21
|
+
KeyedStandardSource,
|
|
22
|
+
MaybeSnapshotSelectorHook,
|
|
23
|
+
RootStandardSourceContribution,
|
|
24
|
+
ScopedStandardSourceBinding,
|
|
25
|
+
SlotScopeAdapter,
|
|
26
|
+
SnapshotSelectorHook,
|
|
27
|
+
StandardSourceBinding,
|
|
28
|
+
} from '@unieai/rabi-client-ui-slots'
|
|
29
|
+
// Type-only service merge for ctx.slots.
|
|
30
|
+
import type {} from '@unieai/rabi-client-ui-renderer/client'
|
|
31
|
+
import { renderSessionArea } from './session-provider.tsx'
|
|
32
|
+
|
|
33
|
+
/** Selector hook over the Session Controller list and current selection. */
|
|
34
|
+
export type UseSessions = SnapshotSelectorHook<SessionListState>
|
|
35
|
+
/** Selector hook over one Session's lifecycle and control state. */
|
|
36
|
+
export type SessionSnapshotSelector = SnapshotSelectorHook<SessionSnapshot>
|
|
37
|
+
/** Public name for the Session lifecycle selector hook. */
|
|
38
|
+
export type UseSession = SessionSnapshotSelector
|
|
39
|
+
|
|
40
|
+
/** Common identity carried by every Session-scoped pending interaction. */
|
|
41
|
+
export interface SessionPendingInteractionBase {
|
|
42
|
+
/** Opaque request identity; a replacement request must use a new key. */
|
|
43
|
+
readonly key: string
|
|
44
|
+
/** Domain-owned presentation discriminator. */
|
|
45
|
+
readonly kind: string
|
|
46
|
+
/** Session whose UI can answer this interaction. */
|
|
47
|
+
readonly sessionId: SessionId
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Declaration-merged map of domain keys to their pending-interaction values. */
|
|
51
|
+
export interface SessionPendingInteractionMap {}
|
|
52
|
+
|
|
53
|
+
/** Union of every pending-interaction value contributed by the assembled Client. */
|
|
54
|
+
export type SessionPendingInteraction =
|
|
55
|
+
[keyof SessionPendingInteractionMap] extends [never]
|
|
56
|
+
? SessionPendingInteractionBase
|
|
57
|
+
: SessionPendingInteractionMap[keyof SessionPendingInteractionMap]
|
|
58
|
+
|
|
59
|
+
/** Independent UI status facts for one Session identity. */
|
|
60
|
+
export interface SessionStatus {
|
|
61
|
+
/** Latest known running state; absent until a baseline or event establishes it. */
|
|
62
|
+
readonly running: boolean | undefined
|
|
63
|
+
/** Highest-precedence domain request currently awaiting user interaction. */
|
|
64
|
+
readonly pendingInteraction: SessionPendingInteraction | undefined
|
|
65
|
+
/** Whether an observed stop outside the main view still needs acknowledgement. */
|
|
66
|
+
readonly completionUnread: boolean
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Current UI status indexed by Session identity. */
|
|
70
|
+
export type SessionStatusSnapshot = ReadonlyMap<SessionId, SessionStatus>
|
|
71
|
+
/** Selector hook over the unified Session UI status snapshot. */
|
|
72
|
+
export type UseSessionStatus = SnapshotSelectorHook<SessionStatusSnapshot>
|
|
73
|
+
|
|
74
|
+
/** Selector hook for explicit or surrounding-Provider Session reference counts. */
|
|
75
|
+
export interface UseSessionRetainInfo {
|
|
76
|
+
/**
|
|
77
|
+
* Read the complete retain information for an explicit Session identity.
|
|
78
|
+
* @param sessionId - Session identity to inspect without retaining it.
|
|
79
|
+
* @returns current local reference counts, or absence while the source is unavailable.
|
|
80
|
+
*/
|
|
81
|
+
(sessionId: SessionId): SessionRetainInfo | undefined
|
|
82
|
+
/**
|
|
83
|
+
* Select from the retain information for an explicit Session identity.
|
|
84
|
+
* @param sessionId - Session identity to inspect without retaining it.
|
|
85
|
+
* @param selector - projection over the current value.
|
|
86
|
+
* @param equal - optional selected-value equality.
|
|
87
|
+
* @returns selected value.
|
|
88
|
+
*/
|
|
89
|
+
<Selected>(
|
|
90
|
+
sessionId: SessionId,
|
|
91
|
+
selector: (value: SessionRetainInfo | undefined) => Selected,
|
|
92
|
+
equal?: (left: Selected, right: Selected) => boolean,
|
|
93
|
+
): Selected
|
|
94
|
+
/**
|
|
95
|
+
* Select from the surrounding Provider's Session retain information.
|
|
96
|
+
* @param selector - projection receiving absence outside a Session binding.
|
|
97
|
+
* @param equal - optional selected-value equality.
|
|
98
|
+
* @returns selected value.
|
|
99
|
+
*/
|
|
100
|
+
<Selected>(
|
|
101
|
+
selector: (value: SessionRetainInfo | undefined) => Selected,
|
|
102
|
+
equal?: (left: Selected, right: Selected) => boolean,
|
|
103
|
+
): Selected
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Publish one pending interaction and define how plugin teardown delegates it. */
|
|
107
|
+
export type PendingInteractionPublisher<T extends SessionPendingInteractionBase> = (
|
|
108
|
+
interaction: T,
|
|
109
|
+
delegate: () => Promise<void>,
|
|
110
|
+
) => () => void
|
|
111
|
+
|
|
112
|
+
interface PendingInteractionEntry<T> {
|
|
113
|
+
readonly interaction: T
|
|
114
|
+
readonly delegate: () => Promise<void>
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
class PendingInteractionDomain<T extends SessionPendingInteractionBase> {
|
|
118
|
+
private readonly values = new Map<string, PendingInteractionEntry<T>>()
|
|
119
|
+
|
|
120
|
+
constructor(
|
|
121
|
+
readonly precedence: (interaction: T) => number,
|
|
122
|
+
private readonly changed: () => void,
|
|
123
|
+
) {}
|
|
124
|
+
|
|
125
|
+
valuesSnapshot(): readonly T[] {
|
|
126
|
+
return [...this.values.values()].map(entry => entry.interaction)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
publish(interaction: T, delegate: () => Promise<void>): () => void {
|
|
130
|
+
if (this.values.has(interaction.key)) {
|
|
131
|
+
throw new Error(`ui-session: duplicate pending interaction key '${interaction.key}'`)
|
|
132
|
+
}
|
|
133
|
+
this.values.set(interaction.key, { interaction, delegate })
|
|
134
|
+
this.changed()
|
|
135
|
+
let active = true
|
|
136
|
+
return () => {
|
|
137
|
+
if (!active) return
|
|
138
|
+
active = false
|
|
139
|
+
if (!this.values.delete(interaction.key)) return
|
|
140
|
+
this.changed()
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Remove every pending value and return the operations that settle their owners. */
|
|
145
|
+
release(): readonly (() => Promise<void>)[] {
|
|
146
|
+
const delegates = [...this.values.values()].map(entry => entry.delegate)
|
|
147
|
+
this.values.clear()
|
|
148
|
+
return delegates
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
declare module '@unieai/rabi-client-ui-slots' {
|
|
153
|
+
interface SlotScopeTargetMap {
|
|
154
|
+
session: SessionReference
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
interface GlobalStandardProps {
|
|
158
|
+
/** Session list and current selection. */
|
|
159
|
+
useSessions: UseSessions
|
|
160
|
+
useSessionStatus: UseSessionStatus
|
|
161
|
+
useSessionRetainInfo: UseSessionRetainInfo
|
|
162
|
+
/** Whether the current Peer may call `action` on one Session resource. */
|
|
163
|
+
useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
interface SessionStandardProps {
|
|
167
|
+
/** Current Session lifecycle and control state. */
|
|
168
|
+
useSession: SessionSnapshotSelector
|
|
169
|
+
/** Current Session identity. */
|
|
170
|
+
sessionId: SessionId
|
|
171
|
+
/** Host-computed projection values addressed by projection key. */
|
|
172
|
+
useProjection: UseProjection
|
|
173
|
+
/** Whether the current Peer may call `action` on this Session resource. */
|
|
174
|
+
useAccess: (action: RemoteEndpoint) => boolean
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
interface SessionMaybeStandardProps {
|
|
178
|
+
/** Current Session state, absent while no Session is selected. */
|
|
179
|
+
useSession: MaybeSnapshotSelectorHook<SessionSnapshot>
|
|
180
|
+
/** Current Session identity, absent while no Session is selected. */
|
|
181
|
+
sessionId: SessionId | undefined
|
|
182
|
+
/** Host-computed projection values; every key is absent without a Session. */
|
|
183
|
+
useProjection: UseProjection
|
|
184
|
+
/** The bound Session's access answer; `undefined` without a Session, which callers treat as not allowed. */
|
|
185
|
+
useAccess: (action: RemoteEndpoint) => boolean | undefined
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
declare module '@unieai/rabi-api-session-controller/client' {
|
|
190
|
+
interface SessionReferenceSourceMap {
|
|
191
|
+
mainView: unknown
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
declare module '@unieai/cordis' {
|
|
196
|
+
interface Context {
|
|
197
|
+
/** Session Controller adapter and session-scoped source registry. */
|
|
198
|
+
uiSession: UiSession
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
type SessionSourceRoster = readonly string[] | undefined
|
|
203
|
+
type StandardMemberKind = 'hook' | 'keyed hook' | 'prop'
|
|
204
|
+
|
|
205
|
+
type SessionSourceRecord<Roster extends SessionSourceRoster, Value> =
|
|
206
|
+
Roster extends readonly string[] ? Readonly<Record<Roster[number], Value>> : never
|
|
207
|
+
|
|
208
|
+
/** Bare values produced by one Session-scoped source contribution. */
|
|
209
|
+
export interface SessionSourceContribution<
|
|
210
|
+
Hooks extends SessionSourceRoster = SessionSourceRoster,
|
|
211
|
+
KeyedHooks extends SessionSourceRoster = SessionSourceRoster,
|
|
212
|
+
Props extends SessionSourceRoster = SessionSourceRoster,
|
|
213
|
+
> {
|
|
214
|
+
readonly hooks?: SessionSourceRecord<Hooks, HostObservable<unknown>>
|
|
215
|
+
readonly keyedHooks?: SessionSourceRecord<KeyedHooks, KeyedStandardSource>
|
|
216
|
+
readonly props?: SessionSourceRecord<Props, unknown>
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Static roster and per-Session resolver for one standard-props contribution. */
|
|
220
|
+
export interface SessionSourceDescriptor<
|
|
221
|
+
Hooks extends SessionSourceRoster = SessionSourceRoster,
|
|
222
|
+
KeyedHooks extends SessionSourceRoster = SessionSourceRoster,
|
|
223
|
+
Props extends SessionSourceRoster = SessionSourceRoster,
|
|
224
|
+
> {
|
|
225
|
+
readonly hooks?: Hooks
|
|
226
|
+
readonly keyedHooks?: KeyedHooks
|
|
227
|
+
readonly props?: Props
|
|
228
|
+
/**
|
|
229
|
+
* Resolve every declared member for one Session binding.
|
|
230
|
+
* @param binding - Controller-owned Session binding.
|
|
231
|
+
* @returns all declared bare sources and stable props.
|
|
232
|
+
*/
|
|
233
|
+
resolve(binding: SessionBinding): SessionSourceContribution<
|
|
234
|
+
NoInfer<Hooks>,
|
|
235
|
+
NoInfer<KeyedHooks>,
|
|
236
|
+
NoInfer<Props>
|
|
237
|
+
>
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
interface RuntimeSessionSourceContribution {
|
|
241
|
+
readonly hooks?: Readonly<Record<string, HostObservable<unknown>>>
|
|
242
|
+
readonly keyedHooks?: Readonly<Record<string, KeyedStandardSource>>
|
|
243
|
+
readonly props?: Readonly<Record<string, unknown>>
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
interface RuntimeSessionSourceDescriptor {
|
|
247
|
+
readonly hooks?: readonly string[]
|
|
248
|
+
readonly keyedHooks?: readonly string[]
|
|
249
|
+
readonly props?: readonly string[]
|
|
250
|
+
resolve(binding: SessionBinding): RuntimeSessionSourceContribution
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
type RuntimePendingDomain = PendingInteractionDomain<SessionPendingInteractionBase>
|
|
254
|
+
|
|
255
|
+
interface MaterializedBinding {
|
|
256
|
+
readonly owner: SessionBinding
|
|
257
|
+
readonly source: BindingSource
|
|
258
|
+
readonly release: () => void
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
interface BindingSource extends HostObservable<StandardSourceBinding> {
|
|
262
|
+
value: StandardSourceBinding
|
|
263
|
+
readonly listeners: Set<() => void>
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const BUILTIN_SOURCE = {
|
|
267
|
+
hooks: ['session'],
|
|
268
|
+
keyedHooks: ['projection'],
|
|
269
|
+
props: ['sessionId'],
|
|
270
|
+
resolve: binding => ({
|
|
271
|
+
hooks: { session: binding.session },
|
|
272
|
+
keyedHooks: { projection: key => binding.session.projections.faceOf(key) },
|
|
273
|
+
props: { sessionId: binding.sessionId },
|
|
274
|
+
}),
|
|
275
|
+
} satisfies SessionSourceDescriptor<
|
|
276
|
+
readonly ['session'],
|
|
277
|
+
readonly ['projection'],
|
|
278
|
+
readonly ['sessionId']
|
|
279
|
+
>
|
|
280
|
+
|
|
281
|
+
/** Session-scoped source roster and renderer adapter. */
|
|
282
|
+
export class UiSession extends Service {
|
|
283
|
+
private readonly descriptors: RuntimeSessionSourceDescriptor[] = [
|
|
284
|
+
BUILTIN_SOURCE,
|
|
285
|
+
]
|
|
286
|
+
private readonly bindings = new WeakMapWithValues<SessionBinding, MaterializedBinding>()
|
|
287
|
+
private readonly absent: BindingSource
|
|
288
|
+
private readonly current: BindingSource
|
|
289
|
+
private readonly pendingDomains: RuntimePendingDomain[] = []
|
|
290
|
+
private pendingSnapshot: ReadonlyMap<SessionId, SessionPendingInteractionBase> = new Map()
|
|
291
|
+
private readonly running = new Map<SessionId, boolean>()
|
|
292
|
+
private readonly completionUnread = new Set<SessionId>()
|
|
293
|
+
private statusSnapshot: SessionStatusSnapshot = new Map()
|
|
294
|
+
private readonly statusListeners = new Set<() => void>()
|
|
295
|
+
private mainRetainId: SessionId | undefined
|
|
296
|
+
private disposeMainRetain = (): void => {}
|
|
297
|
+
private active = true
|
|
298
|
+
/** Root source combining running, pending-interaction, and completion-reminder facts. */
|
|
299
|
+
readonly sessionStatus: HostObservable<SessionStatusSnapshot> = {
|
|
300
|
+
getSnapshot: () => this.statusSnapshot,
|
|
301
|
+
subscribe: (listener) => {
|
|
302
|
+
this.statusListeners.add(listener)
|
|
303
|
+
return () => { this.statusListeners.delete(listener) }
|
|
304
|
+
},
|
|
305
|
+
}
|
|
306
|
+
/** Renderer-facing adapter for `session` and `session-maybe` scopes. */
|
|
307
|
+
readonly adapter: SlotScopeAdapter
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* @param ctx - Client root context.
|
|
311
|
+
* @param sessions - Controller-owned Session object layer.
|
|
312
|
+
*/
|
|
313
|
+
constructor(
|
|
314
|
+
ctx: Context,
|
|
315
|
+
private readonly sessions: ISessions,
|
|
316
|
+
) {
|
|
317
|
+
super(ctx, 'uiSession')
|
|
318
|
+
this.absent = createBindingSource(this.materializeAbsent())
|
|
319
|
+
this.current = createBindingSource(this.absent.value)
|
|
320
|
+
this.adapter = {
|
|
321
|
+
current: this.current,
|
|
322
|
+
bindingSource: target => this.bindingSource(target),
|
|
323
|
+
renderArea: renderSessionArea,
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
ctx.effect(() => {
|
|
327
|
+
const disposeList = sessions.list.subscribe(() => { this.publishMain() })
|
|
328
|
+
const disposeStatus = sessions.list.subscribe(() => { this.reconcileStatus() })
|
|
329
|
+
const disposeRemoteStatus = ctx.remote.$on('api-session/status', (sessionId, running) => {
|
|
330
|
+
this.observeRunning(sessionId, running)
|
|
331
|
+
})
|
|
332
|
+
this.publishMain()
|
|
333
|
+
this.reconcileStatus()
|
|
334
|
+
return () => {
|
|
335
|
+
this.active = false
|
|
336
|
+
disposeList()
|
|
337
|
+
disposeStatus()
|
|
338
|
+
disposeRemoteStatus()
|
|
339
|
+
this.disposeMainRetain()
|
|
340
|
+
const records = [...this.bindings.values]
|
|
341
|
+
this.bindings.clear()
|
|
342
|
+
for (const record of records) record.release()
|
|
343
|
+
}
|
|
344
|
+
}, 'ui-session: Session binding projection')
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* Resolve a stable renderer source for an owned Session reference or explicit absence.
|
|
349
|
+
* @param reference - active reference supplied by the Provider owner, or absence.
|
|
350
|
+
* @returns the binding source, which falls back to the absent projection when its generation ends.
|
|
351
|
+
* @throws when the reference does not belong to the active Controller generation.
|
|
352
|
+
*/
|
|
353
|
+
bindingSource(reference: SessionReference | undefined): HostObservable<StandardSourceBinding> {
|
|
354
|
+
if (!this.active) return this.absent
|
|
355
|
+
if (reference === undefined) return this.absent
|
|
356
|
+
const owner = reference.binding
|
|
357
|
+
if (this.sessions.binding(reference.sessionId) !== owner) {
|
|
358
|
+
throw new Error('ui-session: Session reference is not active in this Controller')
|
|
359
|
+
}
|
|
360
|
+
return this.sourceFor(owner)
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Keep `callback`'s effects installed while the current Peer may call
|
|
365
|
+
* `action` on one Session resource, with the semantics of
|
|
366
|
+
* `ctx.remoteAccess.whenAccess`: `useSessionAccess` answers the same
|
|
367
|
+
* question during render.
|
|
368
|
+
* @param sessionId - the Session resource the guarded effects depend on.
|
|
369
|
+
* @param action - endpoint action the guarded effects depend on.
|
|
370
|
+
* @param callback - creates one disposer or an iterable of disposers.
|
|
371
|
+
* @returns idempotent disposer owned by the caller's Cordis fiber.
|
|
372
|
+
*/
|
|
373
|
+
whenAccess(sessionId: SessionId, action: RemoteEndpoint, callback: () => AccessEffect): () => void {
|
|
374
|
+
// `ctx.get` traces the service to the caller's Context, which then owns the controller.
|
|
375
|
+
const access = this.ctx.get('remoteAccess')
|
|
376
|
+
/* v8 ignore next -- this plugin injects remoteAccess, so the service is active while uiSession is reachable. */
|
|
377
|
+
if (access === undefined) throw new Error('ui-session: whenAccess requires the remoteAccess service')
|
|
378
|
+
return access.whenResourceAccess('session', sessionId, action, callback)
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Register one Session-scoped standard-source contribution.
|
|
383
|
+
* @param descriptor - static member roster and per-binding resolver.
|
|
384
|
+
* @returns disposer owned by the caller's Cordis fiber.
|
|
385
|
+
*/
|
|
386
|
+
provide<
|
|
387
|
+
const Hooks extends SessionSourceRoster = undefined,
|
|
388
|
+
const KeyedHooks extends SessionSourceRoster = undefined,
|
|
389
|
+
const Props extends SessionSourceRoster = undefined,
|
|
390
|
+
>(descriptor: SessionSourceDescriptor<Hooks, KeyedHooks, Props>): () => void {
|
|
391
|
+
const runtimeDescriptor = descriptor as unknown as RuntimeSessionSourceDescriptor
|
|
392
|
+
const dispose = this.ctx.effect(() => {
|
|
393
|
+
this.descriptors.push(runtimeDescriptor)
|
|
394
|
+
try {
|
|
395
|
+
this.rebuildBindings()
|
|
396
|
+
} catch (error) {
|
|
397
|
+
this.descriptors.pop()
|
|
398
|
+
throw error
|
|
399
|
+
}
|
|
400
|
+
return () => {
|
|
401
|
+
const index = this.descriptors.indexOf(runtimeDescriptor)
|
|
402
|
+
this.descriptors.splice(index, 1)
|
|
403
|
+
this.rebuildBindings()
|
|
404
|
+
}
|
|
405
|
+
}, 'uiSession.provide()')
|
|
406
|
+
return () => { void dispose() }
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Register one pending-interaction domain and return its publication function.
|
|
411
|
+
* Domain teardown first removes its visible values, then delegates and awaits
|
|
412
|
+
* every still-active owner request.
|
|
413
|
+
* @param precedence - deterministic cross-domain precedence; larger values win.
|
|
414
|
+
* @returns a function that publishes one interaction and its teardown delegation.
|
|
415
|
+
*/
|
|
416
|
+
registerPendingInteraction<T extends SessionPendingInteractionBase>(
|
|
417
|
+
precedence: (interaction: T) => number,
|
|
418
|
+
): PendingInteractionPublisher<T> {
|
|
419
|
+
const domain = new PendingInteractionDomain(precedence, () => {
|
|
420
|
+
this.publishPendingInteractions()
|
|
421
|
+
})
|
|
422
|
+
const runtimeDomain = domain as unknown as RuntimePendingDomain
|
|
423
|
+
this.ctx.effect(() => {
|
|
424
|
+
this.pendingDomains.push(runtimeDomain)
|
|
425
|
+
this.publishPendingInteractions()
|
|
426
|
+
return async () => {
|
|
427
|
+
const delegates = domain.release()
|
|
428
|
+
const index = this.pendingDomains.indexOf(runtimeDomain)
|
|
429
|
+
this.pendingDomains.splice(index, 1)
|
|
430
|
+
this.publishPendingInteractions()
|
|
431
|
+
await Promise.allSettled(delegates.map(delegate => Promise.resolve().then(delegate)))
|
|
432
|
+
}
|
|
433
|
+
}, 'uiSession.registerPendingInteraction()')
|
|
434
|
+
return (interaction, delegate) => domain.publish(interaction, delegate)
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
private rebuildBindings(): void {
|
|
438
|
+
const absent = this.materializeAbsent()
|
|
439
|
+
const updates = [...this.bindings.values].map(record => ({
|
|
440
|
+
source: record.source,
|
|
441
|
+
value: this.materialize(record.owner),
|
|
442
|
+
}))
|
|
443
|
+
this.absent.value = absent
|
|
444
|
+
for (const { source, value } of updates) source.value = value
|
|
445
|
+
notifySubscribers(this.absent.listeners, '[ui-session] absent binding')
|
|
446
|
+
for (const { source } of updates) {
|
|
447
|
+
notifySubscribers(source.listeners, '[ui-session] Session binding')
|
|
448
|
+
}
|
|
449
|
+
this.publishMain()
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
private sourceFor(owner: SessionBinding): BindingSource {
|
|
453
|
+
const cached = this.bindings.get(owner)
|
|
454
|
+
if (cached !== undefined) return cached.source
|
|
455
|
+
const record = this.createMaterializedBinding(owner)
|
|
456
|
+
this.bindings.set(owner, record)
|
|
457
|
+
return record.source
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
private publishMain(): void {
|
|
461
|
+
if (!this.active) return
|
|
462
|
+
const byId = this.sessions.list.getSnapshot().byId
|
|
463
|
+
const currentId = this.current.value.key as SessionId | undefined
|
|
464
|
+
const currentIsMain = currentId !== undefined
|
|
465
|
+
&& (this.sessions.retainInfo(currentId).getSnapshot().retainedBy.mainView ?? 0) > 0
|
|
466
|
+
const nextId = currentIsMain
|
|
467
|
+
? currentId
|
|
468
|
+
: Object.values(byId).find(candidate => (candidate.retainedBy.mainView ?? 0) > 0)?.id
|
|
469
|
+
this.watchMainRetention(nextId)
|
|
470
|
+
const owner = nextId === undefined ? undefined : this.sessions.binding(nextId)
|
|
471
|
+
const value = owner === undefined ? this.absent.value : this.sourceFor(owner).value
|
|
472
|
+
if (this.current.value === value) return
|
|
473
|
+
this.current.value = value
|
|
474
|
+
notifySubscribers(this.current.listeners, '[ui-session] main binding')
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
private watchMainRetention(sessionId: SessionId | undefined): void {
|
|
478
|
+
if (sessionId === this.mainRetainId) return
|
|
479
|
+
this.disposeMainRetain()
|
|
480
|
+
this.mainRetainId = sessionId
|
|
481
|
+
this.disposeMainRetain = sessionId === undefined
|
|
482
|
+
? () => {}
|
|
483
|
+
: this.sessions.retainInfo(sessionId).subscribe(() => { this.publishMain() })
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
private publishPendingInteractions(): void {
|
|
487
|
+
const next = new Map<SessionId, {
|
|
488
|
+
interaction: SessionPendingInteractionBase
|
|
489
|
+
precedence: number
|
|
490
|
+
}>()
|
|
491
|
+
for (const domain of this.pendingDomains) {
|
|
492
|
+
for (const interaction of domain.valuesSnapshot()) {
|
|
493
|
+
const precedence = domain.precedence(interaction)
|
|
494
|
+
const previous = next.get(interaction.sessionId)
|
|
495
|
+
if (previous === undefined || precedence >= previous.precedence) {
|
|
496
|
+
next.set(interaction.sessionId, { interaction, precedence })
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
const projected = new Map(
|
|
501
|
+
[...next].map(([sessionId, value]) => [sessionId, value.interaction] as const),
|
|
502
|
+
)
|
|
503
|
+
if (samePendingInteractions(this.pendingSnapshot, projected)) return
|
|
504
|
+
this.pendingSnapshot = projected
|
|
505
|
+
this.publishStatus()
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
private observeRunning(sessionId: SessionId, running: boolean): void {
|
|
509
|
+
const previous = this.running.get(sessionId)
|
|
510
|
+
const beforeBaseline = this.sessions.list.getSnapshot().phase === 'pending'
|
|
511
|
+
this.running.set(sessionId, running)
|
|
512
|
+
if (running) this.completionUnread.delete(sessionId)
|
|
513
|
+
else if ((previous === true || (previous === undefined && beforeBaseline))
|
|
514
|
+
&& !this.isMain(sessionId)) this.completionUnread.add(sessionId)
|
|
515
|
+
this.publishStatus()
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
private reconcileStatus(): void {
|
|
519
|
+
const list = this.sessions.list.getSnapshot()
|
|
520
|
+
const present = new Set(Object.keys(list.byId) as SessionId[])
|
|
521
|
+
// Subagent catalog rows and retained subagent fallback rows do not establish Host running state.
|
|
522
|
+
for (const id of list.ids) {
|
|
523
|
+
const row = list.byId[id] as SessionSummary
|
|
524
|
+
const previous = this.running.get(id)
|
|
525
|
+
if (previous === undefined) this.running.set(id, row.running)
|
|
526
|
+
else if (previous !== row.running) this.observeRunning(id, row.running)
|
|
527
|
+
}
|
|
528
|
+
for (const id of present) {
|
|
529
|
+
if (this.isMain(id)) this.completionUnread.delete(id)
|
|
530
|
+
}
|
|
531
|
+
if (list.phase === 'ready') {
|
|
532
|
+
for (const id of this.running.keys()) {
|
|
533
|
+
if (present.has(id)) continue
|
|
534
|
+
this.running.delete(id)
|
|
535
|
+
this.completionUnread.delete(id)
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
this.publishStatus()
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
private isMain(sessionId: SessionId): boolean {
|
|
542
|
+
return (this.sessions.list.getSnapshot().byId[sessionId]?.retainedBy.mainView ?? 0) > 0
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
private publishStatus(): void {
|
|
546
|
+
const ids = new Set<SessionId>([
|
|
547
|
+
...(Object.keys(this.sessions.list.getSnapshot().byId) as SessionId[]),
|
|
548
|
+
...this.running.keys(),
|
|
549
|
+
...this.pendingSnapshot.keys(),
|
|
550
|
+
...this.completionUnread,
|
|
551
|
+
])
|
|
552
|
+
const next = new Map<SessionId, SessionStatus>()
|
|
553
|
+
for (const id of ids) {
|
|
554
|
+
next.set(id, {
|
|
555
|
+
running: this.running.get(id),
|
|
556
|
+
pendingInteraction: this.pendingSnapshot.get(id),
|
|
557
|
+
completionUnread: this.completionUnread.has(id),
|
|
558
|
+
})
|
|
559
|
+
}
|
|
560
|
+
if (sameSessionStatus(this.statusSnapshot, next)) return
|
|
561
|
+
this.statusSnapshot = next
|
|
562
|
+
notifySubscribers(this.statusListeners, '[ui-session] Session status')
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
private createMaterializedBinding(owner: SessionBinding): MaterializedBinding {
|
|
566
|
+
const value = this.materialize(owner)
|
|
567
|
+
this.ctx.slots.bindStoreScope(value)
|
|
568
|
+
const source = createBindingSource(value)
|
|
569
|
+
const releaseEffect = owner.ctx.effect(() => () => {
|
|
570
|
+
if (this.bindings.get(owner) === record) this.bindings.delete(owner)
|
|
571
|
+
source.value = this.absent.value
|
|
572
|
+
notifySubscribers(source.listeners, '[ui-session] Session binding')
|
|
573
|
+
this.publishMain()
|
|
574
|
+
}, `ui-session: binding ${owner.sessionId}`)
|
|
575
|
+
const record: MaterializedBinding = {
|
|
576
|
+
owner,
|
|
577
|
+
source,
|
|
578
|
+
release: () => { void releaseEffect() },
|
|
579
|
+
}
|
|
580
|
+
return record
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
private materialize(binding: SessionBinding): ScopedStandardSourceBinding {
|
|
584
|
+
const hooks: Record<string, HostObservable<unknown>> = {}
|
|
585
|
+
const keyedHooks: Record<string, KeyedStandardSource> = {}
|
|
586
|
+
const props: Record<string, unknown> = {}
|
|
587
|
+
const finalProps = new Set<string>()
|
|
588
|
+
for (const descriptor of this.descriptors) {
|
|
589
|
+
const contribution = descriptor.resolve(binding)
|
|
590
|
+
validateContribution(descriptor, contribution)
|
|
591
|
+
copyDeclared('hook', hooks, descriptor.hooks, contribution.hooks, finalProps)
|
|
592
|
+
copyDeclared('keyed hook', keyedHooks, descriptor.keyedHooks, contribution.keyedHooks, finalProps)
|
|
593
|
+
copyDeclared('prop', props, descriptor.props, contribution.props, finalProps)
|
|
594
|
+
}
|
|
595
|
+
const value: ScopedStandardSourceBinding = {
|
|
596
|
+
key: binding.sessionId,
|
|
597
|
+
ctx: binding.ctx,
|
|
598
|
+
hooks,
|
|
599
|
+
keyedHooks,
|
|
600
|
+
props,
|
|
601
|
+
}
|
|
602
|
+
return value
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
private materializeAbsent(): StandardSourceBinding {
|
|
606
|
+
const hooks: Record<string, undefined> = {}
|
|
607
|
+
const keyedHooks: Record<string, undefined> = {}
|
|
608
|
+
const props: Record<string, undefined> = {}
|
|
609
|
+
const finalProps = new Set<string>()
|
|
610
|
+
for (const descriptor of this.descriptors) {
|
|
611
|
+
declareAbsent('hook', hooks, descriptor.hooks, finalProps)
|
|
612
|
+
declareAbsent('keyed hook', keyedHooks, descriptor.keyedHooks, finalProps)
|
|
613
|
+
declareAbsent('prop', props, descriptor.props, finalProps)
|
|
614
|
+
}
|
|
615
|
+
return { key: undefined, hooks, keyedHooks, props }
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
function createBindingSource(value: StandardSourceBinding): BindingSource {
|
|
620
|
+
const source: BindingSource = {
|
|
621
|
+
value,
|
|
622
|
+
listeners: new Set(),
|
|
623
|
+
getSnapshot: () => source.value,
|
|
624
|
+
subscribe: (listener) => {
|
|
625
|
+
source.listeners.add(listener)
|
|
626
|
+
return () => { source.listeners.delete(listener) }
|
|
627
|
+
},
|
|
628
|
+
}
|
|
629
|
+
return source
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
function validateContribution(
|
|
633
|
+
descriptor: RuntimeSessionSourceDescriptor,
|
|
634
|
+
contribution: RuntimeSessionSourceContribution,
|
|
635
|
+
): void {
|
|
636
|
+
rejectUndeclared('hook', descriptor.hooks, contribution.hooks)
|
|
637
|
+
rejectUndeclared('keyed hook', descriptor.keyedHooks, contribution.keyedHooks)
|
|
638
|
+
rejectUndeclared('prop', descriptor.props, contribution.props)
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
function rejectUndeclared(
|
|
642
|
+
kind: string,
|
|
643
|
+
declared: readonly string[] | undefined,
|
|
644
|
+
values: Readonly<Record<string, unknown>> | undefined,
|
|
645
|
+
): void {
|
|
646
|
+
for (const name of Object.keys(values ?? {})) {
|
|
647
|
+
if (!(declared ?? []).includes(name)) {
|
|
648
|
+
throw new Error(`uiSession.provide: undeclared ${kind} '${name}'`)
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
function copyDeclared<T>(
|
|
654
|
+
kind: StandardMemberKind,
|
|
655
|
+
target: Record<string, T>,
|
|
656
|
+
declared: readonly string[] | undefined,
|
|
657
|
+
values: Readonly<Record<string, T>> | undefined,
|
|
658
|
+
finalProps: Set<string>,
|
|
659
|
+
): void {
|
|
660
|
+
for (const name of declared ?? []) {
|
|
661
|
+
claimStandardProp(kind, name, finalProps)
|
|
662
|
+
const value = values?.[name]
|
|
663
|
+
if (value === undefined) throw new Error(`uiSession.provide: missing ${kind} '${name}'`)
|
|
664
|
+
target[name] = value
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
function declareAbsent(
|
|
669
|
+
kind: StandardMemberKind,
|
|
670
|
+
target: Record<string, undefined>,
|
|
671
|
+
declared: readonly string[] | undefined,
|
|
672
|
+
finalProps: Set<string>,
|
|
673
|
+
): void {
|
|
674
|
+
for (const name of declared ?? []) {
|
|
675
|
+
claimStandardProp(kind, name, finalProps)
|
|
676
|
+
target[name] = undefined
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
function claimStandardProp(kind: StandardMemberKind, name: string, finalProps: Set<string>): void {
|
|
681
|
+
const propName = kind === 'prop' ? name : standardHookPropName(name)
|
|
682
|
+
if (finalProps.has(propName)) {
|
|
683
|
+
throw new Error(`uiSession.provide: duplicate ${kind} '${name}' at prop '${propName}'`)
|
|
684
|
+
}
|
|
685
|
+
finalProps.add(propName)
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
/** Required Controller, renderer, Remote, and access services. */
|
|
689
|
+
export const inject = ['sessions', 'slots', 'remote', 'remoteAccess']
|
|
690
|
+
|
|
691
|
+
/**
|
|
692
|
+
* Install the Session root source and scoped adapter.
|
|
693
|
+
* @param ctx - Client Cordis context.
|
|
694
|
+
*/
|
|
695
|
+
export function apply(ctx: Context): void {
|
|
696
|
+
const service = new UiSession(ctx, ctx.sessions)
|
|
697
|
+
ctx.slots.provideRoot({
|
|
698
|
+
hooks: {
|
|
699
|
+
sessions: ctx.sessions.list,
|
|
700
|
+
sessionStatus: service.sessionStatus,
|
|
701
|
+
},
|
|
702
|
+
keyedHooks: {
|
|
703
|
+
sessionRetainInfo: key => ctx.sessions.retainInfo(key as SessionId),
|
|
704
|
+
sessionAccess: (sessionId, action) => action === undefined
|
|
705
|
+
? undefined
|
|
706
|
+
: ctx.remoteAccess.source('session', sessionId, action),
|
|
707
|
+
},
|
|
708
|
+
} satisfies RootStandardSourceContribution)
|
|
709
|
+
ctx.slots.installScope('session', service.adapter)
|
|
710
|
+
service.provide({
|
|
711
|
+
keyedHooks: ['access'],
|
|
712
|
+
resolve: binding => ({
|
|
713
|
+
keyedHooks: { access: action => ctx.remoteAccess.source('session', binding.sessionId, action) },
|
|
714
|
+
}),
|
|
715
|
+
})
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
function sameSessionStatus(left: SessionStatusSnapshot, right: SessionStatusSnapshot): boolean {
|
|
719
|
+
if (left.size !== right.size) return false
|
|
720
|
+
for (const [id, status] of left) {
|
|
721
|
+
const candidate = right.get(id)
|
|
722
|
+
if (candidate === undefined
|
|
723
|
+
|| candidate.running !== status.running
|
|
724
|
+
|| candidate.pendingInteraction !== status.pendingInteraction
|
|
725
|
+
|| candidate.completionUnread !== status.completionUnread) return false
|
|
726
|
+
}
|
|
727
|
+
return true
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
function samePendingInteractions(
|
|
731
|
+
left: ReadonlyMap<SessionId, SessionPendingInteractionBase>,
|
|
732
|
+
right: ReadonlyMap<SessionId, SessionPendingInteractionBase>,
|
|
733
|
+
): boolean {
|
|
734
|
+
if (left.size !== right.size) return false
|
|
735
|
+
for (const [sessionId, interaction] of left) {
|
|
736
|
+
if (right.get(sessionId) !== interaction) return false
|
|
737
|
+
}
|
|
738
|
+
return true
|
|
739
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Session-owned rendering semantics for the standard SessionProvider seat. */
|
|
2
|
+
import type { ReactNode } from 'react'
|
|
3
|
+
import type {
|
|
4
|
+
SessionAreaProps, StandardSourceBinding,
|
|
5
|
+
} from '@unieai/rabi-client-ui-slots'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Render the selected Session body or its empty branch.
|
|
9
|
+
* @param binding - current Session scope binding.
|
|
10
|
+
* @param props - standard Session area render props.
|
|
11
|
+
* @returns the selected Session subtree.
|
|
12
|
+
*/
|
|
13
|
+
export function renderSessionArea(
|
|
14
|
+
binding: StandardSourceBinding,
|
|
15
|
+
{ empty, children }: SessionAreaProps,
|
|
16
|
+
): ReactNode {
|
|
17
|
+
if (binding.key === undefined) return <>{empty?.() ?? null}</>
|
|
18
|
+
return <>{children}</>
|
|
19
|
+
}
|
package/src/index.ts
ADDED