Skip to content

Commit 8f017d1

Browse files
Merge pull request anomalyco#150 from different-ai/feat/state-arch-rollup
feat: state architecture provider rollout
2 parents a23fe43 + 6de120b commit 8f017d1

14 files changed

Lines changed: 516 additions & 3 deletions

‎package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
"dependencies": {
2828
"@opencode-ai/sdk": "^1.1.19",
2929
"@radix-ui/colors": "^3.0.0",
30+
"@solid-primitives/event-bus": "^1.1.2",
3031
"@solid-primitives/storage": "^4.3.3",
3132
"@tauri-apps/api": "^2.0.0",
3233
"@tauri-apps/plugin-dialog": "~2.6.0",
@@ -51,4 +52,4 @@
5152
]
5253
},
5354
"packageManager": "[email protected]"
54-
}
55+
}

‎pnpm-lock.yaml‎

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src/app/context/global-sdk.tsx‎

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
import { createOpencodeClient, type Event } from "@opencode-ai/sdk/v2/client";
2+
import { createGlobalEmitter } from "@solid-primitives/event-bus";
3+
import { batch, createContext, onCleanup, useContext, type ParentProps } from "solid-js";
4+
5+
import { usePlatform } from "./platform";
6+
import { useServer } from "./server";
7+
8+
type GlobalSDKContextValue = {
9+
url: string;
10+
client: ReturnType<typeof createOpencodeClient>;
11+
event: ReturnType<typeof createGlobalEmitter<{ [key: string]: Event }>>;
12+
};
13+
14+
const GlobalSDKContext = createContext<GlobalSDKContextValue | undefined>(undefined);
15+
16+
export function GlobalSDKProvider(props: ParentProps) {
17+
const server = useServer();
18+
const platform = usePlatform();
19+
const abort = new AbortController();
20+
21+
const eventClient = createOpencodeClient({
22+
baseUrl: server.url,
23+
signal: abort.signal,
24+
fetch: platform.fetch,
25+
});
26+
27+
const emitter = createGlobalEmitter<{ [key: string]: Event }>();
28+
29+
type Queued = { directory: string; payload: Event };
30+
31+
let queue: Array<Queued | undefined> = [];
32+
const coalesced = new Map<string, number>();
33+
let timer: ReturnType<typeof setTimeout> | undefined;
34+
let last = 0;
35+
36+
const keyForEvent = (directory: string, payload: Event) => {
37+
if (payload.type === "session.status") return `session.status:${directory}:${payload.properties.sessionID}`;
38+
if (payload.type === "lsp.updated") return `lsp.updated:${directory}`;
39+
if (payload.type === "todo.updated") return `todo.updated:${directory}:${payload.properties.sessionID}`;
40+
if (payload.type === "mcp.tools.changed") return `mcp.tools.changed:${directory}:${payload.properties.server}`;
41+
if (payload.type === "message.part.updated") {
42+
const part = payload.properties.part;
43+
return `message.part.updated:${directory}:${part.messageID}:${part.id}`;
44+
}
45+
};
46+
47+
const flush = () => {
48+
if (timer) clearTimeout(timer);
49+
timer = undefined;
50+
51+
const events = queue;
52+
queue = [];
53+
coalesced.clear();
54+
if (events.length === 0) return;
55+
56+
last = Date.now();
57+
batch(() => {
58+
for (const entry of events) {
59+
if (!entry) continue;
60+
emitter.emit(entry.directory, entry.payload);
61+
}
62+
});
63+
};
64+
65+
const schedule = () => {
66+
if (timer) return;
67+
const elapsed = Date.now() - last;
68+
timer = setTimeout(flush, Math.max(0, 16 - elapsed));
69+
};
70+
71+
const stop = () => {
72+
flush();
73+
};
74+
75+
void (async () => {
76+
const subscription = await eventClient.event.subscribe(undefined, { signal: abort.signal });
77+
let yielded = Date.now();
78+
79+
for await (const event of subscription.stream as AsyncIterable<unknown>) {
80+
const record = event as Event & { directory?: string; payload?: Event };
81+
const payload = record.payload ?? record;
82+
if (!payload?.type) continue;
83+
84+
const directory = typeof record.directory === "string" ? record.directory : "global";
85+
const key = keyForEvent(directory, payload);
86+
if (key) {
87+
const index = coalesced.get(key);
88+
if (index !== undefined) {
89+
queue[index] = undefined;
90+
}
91+
coalesced.set(key, queue.length);
92+
}
93+
94+
queue.push({ directory, payload });
95+
schedule();
96+
97+
if (Date.now() - yielded < 8) continue;
98+
yielded = Date.now();
99+
await new Promise<void>((resolve) => setTimeout(resolve, 0));
100+
}
101+
})()
102+
.finally(stop)
103+
.catch(() => undefined);
104+
105+
onCleanup(() => {
106+
abort.abort();
107+
stop();
108+
});
109+
110+
const client = createOpencodeClient({
111+
baseUrl: server.url,
112+
fetch: platform.fetch,
113+
throwOnError: true,
114+
});
115+
116+
const value: GlobalSDKContextValue = {
117+
url: server.url,
118+
client,
119+
event: emitter,
120+
};
121+
122+
return <GlobalSDKContext.Provider value={value}>{props.children}</GlobalSDKContext.Provider>;
123+
}
124+
125+
export function useGlobalSDK() {
126+
const context = useContext(GlobalSDKContext);
127+
if (!context) {
128+
throw new Error("Global SDK context is missing");
129+
}
130+
return context;
131+
}

‎src/app/context/global-sync.tsx‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import { createContext, useContext, type ParentProps } from "solid-js";
2+
import { createStore, type SetStoreFunction, type Store } from "solid-js/store";
3+
4+
import type { Message, Part, Session } from "@opencode-ai/sdk/v2/client";
5+
6+
import type { TodoItem } from "../types";
7+
8+
export type WorkspaceState = {
9+
status: "idle" | "loading" | "partial" | "ready";
10+
session: Session[];
11+
session_status: Record<string, string>;
12+
message: Record<string, Message[]>;
13+
part: Record<string, Part[]>;
14+
todo: Record<string, TodoItem[]>;
15+
};
16+
17+
type WorkspaceStore = [Store<WorkspaceState>, SetStoreFunction<WorkspaceState>];
18+
19+
type GlobalSyncContextValue = {
20+
data: Store<{ ready: boolean; error?: string }>;
21+
child: (directory: string) => WorkspaceStore;
22+
};
23+
24+
const GlobalSyncContext = createContext<GlobalSyncContextValue | undefined>(undefined);
25+
26+
const createWorkspaceState = (): WorkspaceState => ({
27+
status: "idle",
28+
session: [],
29+
session_status: {},
30+
message: {},
31+
part: {},
32+
todo: {},
33+
});
34+
35+
export function GlobalSyncProvider(props: ParentProps) {
36+
const [globalStore] = createStore({ ready: true, error: undefined as string | undefined });
37+
const children = new Map<string, WorkspaceStore>();
38+
39+
const child = (directory: string): WorkspaceStore => {
40+
const key = directory || "global";
41+
const existing = children.get(key);
42+
if (existing) return existing;
43+
const store = createStore<WorkspaceState>(createWorkspaceState());
44+
children.set(key, store);
45+
return store;
46+
};
47+
48+
const value: GlobalSyncContextValue = {
49+
data: globalStore,
50+
child,
51+
};
52+
53+
return <GlobalSyncContext.Provider value={value}>{props.children}</GlobalSyncContext.Provider>;
54+
}
55+
56+
export function useGlobalSync() {
57+
const context = useContext(GlobalSyncContext);
58+
if (!context) {
59+
throw new Error("Global sync context is missing");
60+
}
61+
return context;
62+
}

‎src/app/context/local.tsx‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import { createContext, useContext, type ParentProps } from "solid-js";
2+
import { createStore, type SetStoreFunction, type Store } from "solid-js/store";
3+
4+
import type { DashboardTab, DemoSequence, ModelRef, View } from "../types";
5+
import { Persist, persisted } from "../utils/persist";
6+
7+
type LocalUIState = {
8+
view: View;
9+
tab: DashboardTab;
10+
demoMode: boolean;
11+
demoSequence: DemoSequence;
12+
};
13+
14+
type LocalPreferences = {
15+
showThinking: boolean;
16+
modelVariant: string | null;
17+
defaultModel: ModelRef | null;
18+
};
19+
20+
type LocalContextValue = {
21+
ui: Store<LocalUIState>;
22+
setUi: SetStoreFunction<LocalUIState>;
23+
prefs: Store<LocalPreferences>;
24+
setPrefs: SetStoreFunction<LocalPreferences>;
25+
ready: () => boolean;
26+
};
27+
28+
const LocalContext = createContext<LocalContextValue | undefined>(undefined);
29+
30+
export function LocalProvider(props: ParentProps) {
31+
const [ui, setUi, , uiReady] = persisted(
32+
Persist.global("local.ui", ["openwork.ui"]),
33+
createStore<LocalUIState>({
34+
view: "onboarding",
35+
tab: "home",
36+
demoMode: false,
37+
demoSequence: "cold-open",
38+
}),
39+
);
40+
41+
const [prefs, setPrefs, , prefsReady] = persisted(
42+
Persist.global("local.preferences", ["openwork.preferences"]),
43+
createStore<LocalPreferences>({
44+
showThinking: false,
45+
modelVariant: null,
46+
defaultModel: null,
47+
}),
48+
);
49+
50+
const ready = () => uiReady() && prefsReady();
51+
52+
const value: LocalContextValue = {
53+
ui,
54+
setUi,
55+
prefs,
56+
setPrefs,
57+
ready,
58+
};
59+
60+
return <LocalContext.Provider value={value}>{props.children}</LocalContext.Provider>;
61+
}
62+
63+
export function useLocal() {
64+
const context = useContext(LocalContext);
65+
if (!context) {
66+
throw new Error("Local context is missing");
67+
}
68+
return context;
69+
}

0 commit comments

Comments
 (0)