Skip to content

fix(site): update useAgentLogs to make it more testable and add more tests #19126

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 25 commits into
base: main
Choose a base branch
from

Conversation

Parkreiner
Copy link
Member

@Parkreiner Parkreiner commented Aug 2, 2025

Take 2
Closes coder/internal#644

Changes made

  • Updated how useAgentLogs was defined to make it easier to inject specific data dependencies (basically making the hook more unit-testable)
  • Simplified the hook API to limit the amount of scope of data it needs to work
  • Added more test cases, and re-enabled the one test case we had previously disabled
  • Extracted our mock websocket code into a separate file, and added more methods to it
  • Updated all runtime code to accommodate new changes

@Parkreiner Parkreiner self-assigned this Aug 2, 2025
@Parkreiner Parkreiner requested a review from aslilac as a code owner August 2, 2025 20:59
const stableMetadataResult = useMemo<UseEmbeddedMetadataResult>(() => {
return {
metadata,
clearMetadataByKey: manager.clearMetadataByKey,
};
}, [metadata]);
}, [manager, metadata]);
Copy link
Member Author

@Parkreiner Parkreiner Aug 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A case where realistically, the value of manager won't ever change, but it technically can, since function parameters are reassignable. So better to add it to the dependencies for correctness

const logListRef = useRef<List>(null);
const logListDivRef = useRef<HTMLDivElement>(null);
const startupLogs = useMemo(() => {
const allLogs = agentLogs || [];
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agentLogs is no longer nullable, so a bunch of logic can be removed

@@ -1,60 +1,147 @@
import { renderHook, waitFor } from "@testing-library/react";
Copy link
Member Author

@Parkreiner Parkreiner Aug 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enough changed with the test file that it honestly might not even be worth looking at the old version of the code

@Parkreiner Parkreiner changed the title fix: update useAgentLogs to make it more testable and add more tests fix(site): update useAgentLogs to make it more testable and add more tests Aug 4, 2025
publishError: (event: Event) => void;
publishClose: (event: CloseEvent) => void;
publishOpen: (event: Event) => void;
readonly isConnectionOpen: boolean;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Setup is 99% the same from the old file, just with the addition of this getter method

Copy link
Member

@aslilac aslilac left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this mock WebSocket implementation needs some tests of its own, and is probably worth its own PR as well. @jaaydenh has been working on a similar refactor of some other tests that I think uses a copy of this WebSocket mock. It'd be nice to sync on that so that we don't duplicate effort, and then we can get everyones tests reviewed. 😄

@Parkreiner
Copy link
Member Author

@aslilac Yeah, totally fair. I'll check with Jaayden

Parkreiner added a commit that referenced this pull request Aug 7, 2025
Needed for #19126 and
#18679

## Changes made
- Moved `createWebSocket` to dedicated file and addressed edge cases for
making it a reliable mock
- Added test cases to validate mock functionality
@Parkreiner Parkreiner requested a review from aslilac August 7, 2025 21:00
Copy link
Member

@aslilac aslilac left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd love to have a story for the logs_overflowed state

(sorry if this is asking a lot, I just keep seeing things that'd be nice to clean up everywhere)

}
return [
...agentLogs,
{
id: -1,
level: "error",
output:
"Startup logs exceeded the max size of 1MB, and will not continue to be written to the database! Logs will continue to be written to the /tmp/coder-startup-script.log file in the workspace.",
created_at: new Date().toISOString(),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we're leaking in here. I feel like this should be...

Suggested change
created_at: new Date().toISOString(),
created_at: agentLogs.at(-1).created_at,

since that's probably more "correct" and deterministic


function generateMockLogs(
logCount: number,
baseDate = new Date(),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
baseDate = new Date(),
baseDate = new Date("Thu, 07 Aug 2025 21:38:12 GMT"),

as an example, how about just right now

}
return [
...agentLogs,
{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also I know it was already like this, but is shoving a log entry on the end really the best way to do this?

this startupLogs value eventually gets passed to AgentLogs below. what if we just passed agentLogs in unmodified and added an overflowed prop that shows the warning?

Comment on lines +95 to +101
for (const log of reversed) {
act(() => {
serverResult.current?.publishMessage(
new MessageEvent("message", { data: JSON.stringify([log]) }),
);
});
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
for (const log of reversed) {
act(() => {
serverResult.current?.publishMessage(
new MessageEvent("message", { data: JSON.stringify([log]) }),
);
});
}
await act(async () => {
for (const log of reversed) {
serverResult.current?.publishMessage(
new MessageEvent("message", { data: JSON.stringify([log]) }),
);
}
});

I'm still trying to build up an intuition for act, but I noticed while looking at the docs that they now promote calling it with an async function and awaiting so I'm wondering if this patch makes sense.

reference: https://react.dev/reference/react/act

});

const errorEvent = new Event("error");
act(() => serverResult.current?.publishError(errorEvent));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
act(() => serverResult.current?.publishError(errorEvent));
await act(() => serverResult.current?.publishError(errorEvent));

expect(onError).toHaveBeenCalledTimes(1);
});

it("Clears logs when hook becomes disabled (protection to avoid duplicate logs when hook goes back to being re-enabled)", async () => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
it("Clears logs when hook becomes disabled (protection to avoid duplicate logs when hook goes back to being re-enabled)", async () => {
// This is a protection to avoid duplicate logs when the hook is re-enabled
it("Clears logs when hook becomes disabled", async () => {

import type { WorkspaceAgent, WorkspaceAgentLog } from "api/typesGenerated";
import {
type WatchWorkspaceAgentLogsParams,
watchWorkspaceAgentLogs,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if rather than all of this factory stuff we could just mock watchWorkspaceAgentLogs. I think that might make it easier to get the publisher value too, but can't say for sure.

const initialEvent = new MessageEvent("message", {
data: JSON.stringify(initialLogs),
});
act(() => serverResult.current?.publishMessage(initialEvent));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
act(() => serverResult.current?.publishMessage(initialEvent));
await act(async () => serverResult.current?.publishMessage(initialEvent));

const newEvent = new MessageEvent("message", {
data: JSON.stringify(newLogs),
});
act(() => serverResult.current?.publishMessage(newEvent));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
act(() => serverResult.current?.publishMessage(newEvent));
await act(async () => serverResult.current?.publishMessage(newEvent));

return <Loader />;
}

const logs = useAgentLogs(agent.id, true);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

another "I know it was already like this" moment but nondescript booleans like this are dreadful. I'd love to see this argument go from boolean to { enabled: boolean = true } (similar to what react-query does, default to on, optimized for the happy path)

function mountHook(options: MountHookOptions): MountHookResult {
const { initialAgentId, enabled = true, onError = jest.fn() } = options;

const serverResult: ServerResult = { current: undefined };
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if we stick with this we could just use createRef and React.RefObject<MockWebSocketServer> instead of making our own type here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

flake: useAgentLogs
2 participants
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy