Skip to content

Commit b1d572f

Browse files
committed
chore: move AgentMetadata to OWWS
1 parent da96d23 commit b1d572f

File tree

1 file changed

+28
-21
lines changed

1 file changed

+28
-21
lines changed

site/src/modules/resources/AgentMetadata.tsx

Lines changed: 28 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
useState,
1818
} from "react";
1919
import { MONOSPACE_FONT_FAMILY } from "theme/constants";
20+
import type { OneWayWebSocket } from "utils/OneWayWebSocket";
2021

2122
type ItemStatus = "stale" | "valid" | "loading";
2223

@@ -48,41 +49,47 @@ export const AgentMetadata: FC<AgentMetadataProps> = ({
4849
}) => {
4950
const [metadata, setMetadata] = useState<
5051
WorkspaceAgentMetadata[] | undefined
51-
>(undefined);
52+
>(storybookMetadata);
5253

5354
useEffect(() => {
55+
// Even though we're using storybookMetadata as the initial value of the
56+
// `metadata` state, we can't sync on `metadata` itself. If we did, the
57+
// moment we update the state with a new event, we would re-trigger the
58+
// effect and immediately destroy the connection
5459
if (storybookMetadata !== undefined) {
55-
setMetadata(storybookMetadata);
5660
return;
5761
}
5862

59-
let timeout: ReturnType<typeof setTimeout> | undefined = undefined;
63+
let timeoutId: number | undefined = undefined;
64+
let latestSocket: OneWayWebSocket | undefined = undefined;
6065

61-
const connect = (): (() => void) => {
62-
const source = watchAgentMetadata(agent.id);
66+
const createNewConnection = () => {
67+
const socket = watchAgentMetadata(agent.id);
68+
latestSocket = socket;
6369

64-
source.onerror = (e) => {
70+
socket.addEventListener("error", (e) => {
6571
console.error("received error in watch stream", e);
6672
setMetadata(undefined);
67-
source.close();
73+
socket.close();
6874

69-
timeout = setTimeout(() => {
70-
connect();
71-
}, 3000);
72-
};
75+
timeoutId = window.setTimeout(() => {
76+
createNewConnection();
77+
}, 3_000);
78+
});
7379

74-
source.addEventListener("data", (e) => {
75-
const data = JSON.parse(e.data);
76-
setMetadata(data);
80+
socket.addEventListener("message", (e) => {
81+
try {
82+
const data = JSON.parse(e.data);
83+
setMetadata(data);
84+
} catch (err) {}
7785
});
78-
return () => {
79-
if (timeout !== undefined) {
80-
clearTimeout(timeout);
81-
}
82-
source.close();
83-
};
8486
};
85-
return connect();
87+
88+
createNewConnection();
89+
return () => {
90+
window.clearTimeout(timeoutId);
91+
latestSocket?.close();
92+
};
8693
}, [agent.id, storybookMetadata]);
8794

8895
if (metadata === undefined) {

0 commit comments

Comments
 (0)