Skip to content

chore: initial state machine plumbing - #2046

Merged
lukasIO merged 22 commits into
mainfrom
lukas/signal-client-sm
Aug 20, 2026
Merged

lukasIO merged 22 commits into
mainfrom
lukas/signal-client-sm

Conversation

@lukasIO

@lukasIO lukasIO commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

No description provided.

@changeset-bot

changeset-bot Bot commented Aug 13, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: ce3f56a

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
livekit-client Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@github-actions

github-actions Bot commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

size-limit report 📦

Path Size
dist/livekit-client.esm.mjs 109.38 KB (0%)
dist/livekit-client.umd.js 118.38 KB (0%)

@lukasIO
lukasIO marked this pull request as ready for review August 18, 2026 16:28
devin-ai-integration[bot]

This comment was marked as resolved.

@1egoman 1egoman left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This generally looks like a great start to me!

One thing I would find really helpful would be some sort of way to visualize the state machine. If there isn't a tool already which can read the machina state machine and generate a mermaid / graphviz / etc type visualization from it, I suspect this would be pretty easy to add. I'm thinking some sort of small script which could import in the SignalClient (and in the future, other state machines all combined together), convert to mermaid or graphviz, then generate a big svg. This is also something a LLM could use to generate diagrams for describing potential changes.

The dream / probably a stretch goal would be some way for the example app to be able to show the state machine live so as you test out scenarios you can actually watch the "active" state propagate through the state machine interactively. At a past job I did this for a large distributed state machine which was not too dissimilar from livekit's domain and it proved invaluable both for engineering understanding and explaining failure modes to less technical folks.

Comment thread src/api/SignalClient.ts Resolved
Comment thread src/api/SignalClientStateMachine.ts Outdated
Comment on lines +73 to +83

const signalStates = {
new: {
connect: startConnect,
reconnect: startReconnect,
close: requestClose,
},
connecting: {
connect: startConnect,
reconnect: startReconnect,
connectComplete: 'connected',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nitpick: you may consider breaking out some of these repeated states instead into some more "component level" objects which can be spread in rather than breaking out hte functions individually. As is I find myself going back and forth a lot between function and state transition map when reasoning about this.

Suggested change
const signalStates = {
new: {
connect: startConnect,
reconnect: startReconnect,
close: requestClose,
},
connecting: {
connect: startConnect,
reconnect: startReconnect,
connectComplete: 'connected',
const common = {
connect: on<'connect'>(({ ctx }) => {
ctx.attemptId += 1;
ctx.lastError = undefined;
return 'connecting';
}),
reconnect: on<'reconnect'>(({ ctx }) => {
ctx.attemptId += 1;
ctx.lastError = undefined;
return 'reconnecting';
}),
close: on<'close'>(({ ctx }, event) => {
ctx.closeReason = event.reason;
return 'disconnecting';
}),
};
const signalStates = {
new: common,
connecting: {
...common, // etc
connectComplete: 'connected',

@lukasIO lukasIO Aug 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

not opposed to that, what I like more about the current way of defining it, is that all possible transitions are directly visible within the definition. Spreading a common set would make that opaque. I'll merge it like it is for now, but very open to discuss this more

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

@lukasIO

lukasIO commented Aug 19, 2026

Copy link
Copy Markdown
Contributor Author

One thing I would find really helpful would be some sort of way to visualize the state machine.

added via pnpm examples:machine

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Devin Review found 1 new potential issue.

View 2 additional findings in Devin Review.

Open in Devin Review

Comment on lines +163 to +166
picker.innerHTML = machines
.map((machine, index) => `<option value="${index}">${machine.name}</option>`)
.join('');
picker.hidden = machines.length < 2;

@devin-ai-integration devin-ai-integration Bot Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟨 Machine names are injected into the inspector page as raw HTML

The inspector builds the machine picker by interpolating each registration's name straight into innerHTML (examples/state-machine/inspector.ts:163-165), so any registration name containing markup is parsed as HTML rather than text. The log list does the same with input names (examples/state-machine/inspector.ts:255-264). Today all names are hardcoded in examples/state-machine/machines.ts, so this is not exploitable, but it is an unsafe pattern for a developer tool that is meant to be pointed at arbitrary machines.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +1 to +8
# machina inspector

Renders a [machina](https://machina-js.org) FSM and lets you drive it by hand: fire inputs, watch
the state move, and see what the machine does with an input it does not want.

```bash
pnpm examples:machine
```

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

thought: This is definitely useful and I think is a fine start if you want to leave it here for now!

But to clarify my previous suggestion - I think this would be a lot more valuable if it were actually hooked up to an actual client sdk. So instead of manually triggering connect / connectComplete / etc events, you could connect a client, test different scenarios (either via "simulate scenario", or by actually causing them), and watch the state machine to make sure it does the "right thing" in each case. Especially as more of the connection management logic moves into explicit state machines and the whole thing grows, I think a tool like this will be required for effective debugging.

Comment thread src/api/SignalClient.ts
Comment on lines +499 to +509
// A failed upgrade closes the socket, so `opened` and `closed` settle for the same cause — but
// only the `opened` path can classify it (a 401 is known after asking the validate endpoint).
// Noting the failure *before* the close handler is registered means it runs first, so a close
// that merely reflects a failed upgrade stands down and lets the classified error reach the
// caller. Any other close still fails the attempt straight away: after a successful upgrade
// nothing else would, short of the first-message timeout.
let upgradeFailed = false;
this.ws.opened.catch(() => {
upgradeFailed = true;
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

thought: Seeing this makes me wonder if it's worth there being distinct events for each type of "close", or maybe some sort of enum value on the event which captures a "close reason". It doesn't seem like it's required for a logic specific reason today but I think the two big advantages are 1) capturing context in events for debugging, and 2) building ahead a bit for when there inevitably will need to be different logic in different failure modes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

do you mean on the ws/transport level?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

No, I mean at the state machine level. At the past job I've referred to a few times now, we had found it really useful to capture as much context on each event as possible about the current state as it was fairly useful for debugging. But also this was just a passing thought and if there isn't a concrete reason to add extra metadata to the events today feel free to disregard.

Comment on lines +20 to +24
function machineIn(state: SignalLifecycleState): SignalMachine {
const machine = createSignalMachine();
switch (state) {
case 'new':
break;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

question: Is this really the best way to initialize a state machine at an arbitrary state? I know with xstate there is a way that you can start a machine at any arbitrary state as a one-liner - a quick search points me at machine.resolveState.

Is there something similar with machina? If not, I wonder if you can set some internal variable on the machina state machine class to emulate this. The concern I have with what you have here is that all these cases are something we are going to have to keep up to date, and especially as the state machine grows, that is going to become quite burdensome.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

yeah, it isn't pretty. changed it to pass the initial state to the create function with new being the default

Comment on lines +60 to +70
/**
* Every state/input pair and what it resolves to. Asserted exhaustively below, and used as the
* oracle for the random walks, so adding a state or an input cannot silently leave a hole.
*/
const documentedTransitions: Record<string, Record<string, TransitionTarget>> = {
// Establishing a session is legal exactly where no transport and no attempt are in play: `new`,
// `offline`, `closed`. Elsewhere it is a caller error, and `SignalClient` refuses rather than
// opening a transport the lifecycle would not own — except from `disconnecting`, which it waits out.
new: {
connect: 'connecting',
close: 'disconnecting',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

question: How useful is this in the tests? Like my previous comment, I worry about keeping this up to date, especially since these are Record<string, ..>s (so there won't be a type error if new states are added). It looks like these are only used in a few tests which validate that the whole state machine exactly matches with all transitions lining up, but IMO, I'm not sure that's all that useful. I think the most valuable tests are ones which start at a state, and drive it through a series of steps and make sure that the state is correct at each step and that any side effects have been accomplished.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think the randomWalks test is where this is most useful.
I'm not super concerned with keeping it up to date, as the tests would fail if we change something without updating the documented transitions here

Comment on lines +240 to +249
it('ignores a transport that has already been replaced', () => {
const machine = machineIn('connected');
const staleAttemptId = machine.context.attemptId;

// a newer attempt takes over, then the old socket reports its close
send(machine, { type: 'reconnect' });
send(machine, { type: 'transportFailed', attemptId: staleAttemptId, reason: 'late close' });

expect(machine.currentState()).toBe('reconnecting');
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is I think the most useful type of test here!

One small thought though - I think something higher level than this (ie, more like an integration test where you are interacting with either SignalClient or the SDK's user facing interface) would be even more valuable. As is, I think it's more likely that some side effect code around the state machine is accidentally broken than removing a state transition itself. So ie, maybe add some assertions around the socket state here, etc.

Or maybe the thing to do here is to eventually add some internal state machine state assertions (probably by reaching into some private members in a class) to the e2e tests to make sure it's going down the right paths.

@lukasIO lukasIO Aug 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

yeah, that's what the test in SignalClient.test.ts and SignalClient.test.ts are supposed to do.

So ie, maybe add some assertions around the socket state here, etc.

The socket isn't part of the machine, so I'm not sure what exactly you're suggesting.

@1egoman 1egoman Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The socket isn't part of the machine, so I'm not sure what exactly you're suggesting.

Here is my thought rephrased - checking to make sure the state machine goes through each state transition successfully is somewhat valuable but I suspect less so in practice.

What I think is more likely to break is all the code that runs as part of a state transition - this likely isn't part of the state machine directly. What a test that exercises this would look like:

  1. Create a new room, validate the socket is closed
  2. Call room.connect()
  3. Make sure the state machine is driven through connect -> connecting -> connected.
  4. Validate the socket is open and in a valid state

So you are testing the state machine, but not as directly as you are here. And exactly how the state machine works could change (ie, you could add an intermediate state in between connecting and connected) and the test wouldn't immediately break (or if it would break, it would be very easy to fix), since it's checking user visible behavior is working as expected.


describe('close', () => {
it('is legal from every state that owns a transport or an attempt', () => {
for (const state of ['new', 'connecting', 'connected', 'offline', 'reconnecting'] as const) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

thought: I wonder if there's some way you could make these lists exhaustive (is there some way to determine statically whether a state has a transport associated?), so that when a new entry is added, there's a type error that ensures that somebody also adds the new entry to this list.

Comment on lines +421 to +445

// Random input sequences, checked against the properties the lifecycle is supposed to hold.
// Seeded, so a failure replays exactly; the seed is reported in the failure either way.
describe('random walks', () => {
it('only ever takes transitions the table documents', () => {
const { factory, inputs } = walkSetup();
walkAll(factory, {
seed: 20260818,
walks: 200,
maxSteps: 25,
inputs,
invariant({ state, previousState, input }) {
const actual: TransitionTarget =
state === previousState ? 'ignored' : (state as TransitionTarget);
const allowed = payloadDependent[`${previousState}.${input}`] ?? [
documentedTransitions[previousState]?.[input],
];
if (!allowed.includes(actual)) {
throw new Error(
`${previousState} --${input}--> ${state}, but the table documents ${allowed.join(' or ')}`,
);
}
},
});
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nitpick: Though these seem to have seeds, it does somewhat worry me that code doing something non deterministic is in a unit test.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

do you have an alternative suggestion or do you generally think this sort of test isn't useful?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Let's chat about it in our next 1:1, I want to hear your thoughts in higher fidelity. Right now I am skeptical but I think I could be convinced.

| { type: 'reconnectFailed'; error?: unknown; recoverable: boolean }
/** The transport identified by `attemptId` was lost (unexpected ws close, ping timeout). */
| { type: 'transportFailed'; attemptId: number; reason: string }
| { type: 'close'; reason: string }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Ah, per my previous comment - it looks like close does have a reason! I think making it an enum (along with other reason fields here as well) though would be even better than an arbitrary string.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

yeah, enum would be even better. Will leave it as a string for now as there's some sections where we extract the reason from thrown errors via their message. So "reason" here is more like "friendly error message".

@lukasIO
lukasIO merged commit 016cf1c into main Aug 20, 2026
7 checks passed
@lukasIO
lukasIO deleted the lukas/signal-client-sm branch August 20, 2026 14:47
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.

2 participants