Brian Lovin
/
Hacker News
Daily Digest email

Get the top HN stories in your inbox every day.

davidkpiano

Glad to see statecharts still getting attention!

I created XState, a JS/TS library for authoring, executing, and visualizing state machines/statecharts: https://github.com/statelyai/xstate

I've been working on it for 10+ years. The main thing I've learned is that statecharts are most valuable when they're treated as executable behavior, not just documentation.

That doesn't mean you need to use them everywhere or model everything with them. They're most useful when you have behavior where the answer to "what happens next?" depends on both the current state & the event. A statechart can act as an oracle for questions like: "Given I'm in this state, when this event happens, what is the next state, and what effects should run?"

I'm close to releasing an alpha of the next major version of XState, focused on better ergonomics, type safety, and composability, as well as a new visualizer/editor.

There's also an open-source basic statechart visualizer here: https://sketch.stately.ai

For the formal/spec side, SCXML is worth reading: https://www.w3.org/TR/scxml

Also worth reading the original paper by David Harel: https://www.weizmann.ac.il/math/harel/sites/math.harel/files...

jacobbennett

You were the reason I first discovered state machines!

This was a talk I gave at Laracon that was my stab at distilling my thinking about State Machines, State Charts etc.

https://www.youtube.com/watch?v=1A1xFtlDyzU

davidkpiano

I loved this talk!

kayo_20211030

For the clojure folks there's https://github.com/fulcrologic/statecharts which a pretty sophisticated implementation that removes the XML requirement (particularly for executable content), yet remaining close to SCXML. XState even gets a reference in the prior art section.

embedding-shape

And for those of us who want to avoid/are allergic to XML (& SCXML -_-), there is clj-statecharts too (https://lucywang000.github.io/clj-statecharts/docs/get-start...), I've always found it slightly more ergonomic and their codebase is a bit more intuitive and simpler than Fulcro's

egeozcan

I had used (and would gladly still use) XState, without even knowing about what "statecharts" even means.

I used it with lit.js to help with a drawer-like navigation component that reacts to page width and has many props and internal states. I can't even think how horrible it'd have been without XState. Thank you very much!

c01nd01r

With all respect to xstate, if you don't need complex nested state machines, you should check out robot3.js. The automatic TS type inference makes it pretty handy for the spots where you want a bit of state machine logic.

davidkpiano

There is also @xstate/store for simple event-driven stores and atoms; just as simple as Zustand + Jotai: https://stately.ai/docs/xstate-store

dkersten

I’m a big fan of @xstate/store!

jakobloekke

Xstate has helped me clean up some hairy situations in the past. Looking forward to the next version, and thanks for your great work!

miketery

XState is awesome, made a complex decentralized key sharing scheme a breeze.

chrisweekly

XState is an awesome library! Stoked to hear there's a new major version and visualizer coming. :)

jtesp

nice thanks. been looking for a rust equivalent

embedding-shape

2 hours and not a single comment yet?! At one point, Statecharts seemed to be getting traction in the frontend/UI ecosystem, albeit tiny traction. Leveraging state machines (and particular Statecharts, which is basically compositions of state machines) for UI interactions makes complex flows so much easier to reason about! However, seems the traction eventually disappeared for unknown reasons, sadly.

If this is the first time you're hearing about Statecharts, I highly recommend the book "Constructing the user interface with statecharts" by Ian Horrucks (https://archive.org/details/isbn_9780201342789/mode/2up) which yes, is from 1999, but probably the best introduction for how to actually apply and use Statecharts.

larodi

Not sure about the charts themselves, but it helps structure code and logic better if a clear description of possible states (of phenomena) is provided and reasoned about.

Naturally, as the author notes, we are using states in our programs. Three kinds at least

- current program state in the complex space-of-states the program can have - most properties (and vars) are expect to undergo several states, and enumerable denotes a state. - every program traversing a graph for something, essentially runs a state machine of some sort

Indeed a user interface can benefit from having a FSM run it, given interfaces guide the end-user through predefined states from which he navigates into other states (which show/hide a set of widgets and wire them with data).

davidkpiano

Statecharts are still getting some traction! XState has over 4 million weekly npm downloads. Animation tools like Rive & LottieFiles heavily advertise state machine capabilities. AI tools like LangGraph are built on state machine foundations.

It'll take some time for those apps/tools to realize the full potential of statecharts, but it's a good start.

embedding-shape

No doubt state machines are as popular as they've always been :) I was talking about statecharts specifically, not just state machines in general.

sph

> Statecharts seemed to be getting traction in the frontend/UI ecosystem

Yes, I stumbled upon statecharts checking out this Godot plugin: https://github.com/derkork/godot-statecharts

brandensilva

I've been wanting to code up an AI flavor wrapper around state machines that will be visible as an AI generated image in PRs.

I often have my AI code output one just to make sure my logic feels more sound. Along with mermaid charts if I need to toy around or drop into stately for more power.

ZihangZ

Small caution from using agents here: the useful chart is the one generated from code, tests, or traces, not the one the model draws from its own explanation.

I've had models produce very reasonable Mermaid diagrams that matched the intended design but not the actual program. It felt helpful until I realized I was reviewing the plan twice and the implementation zero times.

For PRs I'd rather render the diagram from the executable state machine itself — at least then drift in the chart means drift in behavior, and you can't review one without the other.

ronin_niron

One thing usually skipped in primers: history pseudo-states (H, H) make a statechart formally non-deterministic from outside. The pitch is "current state is a pure function of inputs" — history breaks that. Entering a parent via `H` puts you in whichever child was active last, so the same event from the same outer state can land you in two different inner states. That latent "last-active child" IS state, just state nobody draws on the diagram. Harel's original paper acknowledges it; SCXML and XState both implement it; nobody really talks about it. So if you're using deep history (H) to preserve subtree state across re-entry, you've moved the bookkeeping into the chart engine — fine, but the picture alone no longer tells the full story, and history transitions need their own tests like any other piece of state.

froh

hm

"inputs" can refer to just current and future inputs --- or it refers to the totality of inputs, including the inputs leading up to "here".

in the latter interpretation the machine is perfectly deterministic. and the "deep history" pointer simply is part of the state machine.

ronin_niron

Fair pushback - I was loose with "inputs". Formally yes: if you fold input history into the state itself, every deterministic FSM stays deterministic, H pseudo-states included. The narrower point I was trying to make is that the diagram isn't a complete representation once H is involved. From the practical reading of statecharts - "look at the chart and predict next state given a transition" - H breaks that without showing what it added. The latent state exists but isn't drawn. So the formalism is sound; the visualization is incomplete.

setr

Going solely off your description of the scenario; couldn’t you trivially model any history (H,H) node as two nodes —> (A, H’) —-> (H’, H) —> (H, B), and have it be deterministic again

I’m essentially thinking of H’ as a write-ahead-log prefixing any node

ronin_niron

Yes, you can — that's effectively what "expanding" the chart looks like. With a parent of N children you need N target nodes (one per possible "last-active" child) with deep history the cardinality is the size of the subtree's leaf set, which is exponential in nesting depth. That's exactly the explosion flat FSMs hit when you compose them — and the reason Harel introduced H notation in the first place, to elide it. So determinism is recoverable, just at the cost of the very property state charts were designed to deliver.

hasyimibhar

I wonder if it's possible to combine statecharts with durable execution engines like Temporal, DBOS, Restate, etc. At work we use Cloudflare Workflows for managing onboarding and payment workflows. It generates flowchart diagram that is useful for quickly reasoning about what the workflow does, which I guess is what statecharts is trying to achieve.

_ben_

I’m building Zindex [1], which is aimed at this exact “visual representation of executable workflows” layer.

What I'm solving for is AI-generated diagrams are usually one-shot: Mermaid/SVG/PNG gets emitted, but there’s no durable diagram state to update, validate, diff, or reuse.

Zindex makes the diagram itself structured state. Agents use a Diagram Scene Protocol (DSP) to patch nodes, edges, groups, relationships, constraints, and revisions; Zindex handles validation, layout, rendering, versioning, and storage.

So for Temporal/DBOS/Restate/Cloudflare Workflows, I’d imagine Zindex sitting beside the durable execution engine: the engine remains the source of truth for execution, while Zindex maintains the persistent, inspectable visual model derived from code or execution history.

[1] https://zindex.ai/

brandensilva

Yeah its bothered me that workflows get all the limelight while state machines are more than capable. They just need durable execution for state charts. I think Cloudflare was going down the durable object actor model for a bit, but not sure if they abandoned that coded project.

apsurd

When you say "it generates flowchart diagrams…" what exactly is generating them? Is it built into cloudflare workers or is it something your team created?

phpnode

Cloudflare workers shows a visualisation of your workflow in their dashboard, but it’s imperfect

rleigh

Let me just throw in:

ETL State Chart and Hierarchial FSM https://www.etlcpp.com/state_chart.html and https://www.etlcpp.com/hfsm.html

Quantum Leaps https://www.state-machine.com

I've used them primarily in safety-critical systems where complexity, timing and the ability to effectively verify behaviour is obviously important. Being able to separate the decision-making from the actions is a great aid. Having to strip back the decision making to "what do I do next" when I'm in this state and this event occurs is a bit different to how most programs are structured, but really does aid separation and makes it easy to reason about behaviour under different conditions.

brandensilva

I've always been a fan of state machines and have hoped for their adoption to grow.

Having visual understanding of state is becoming increasingly important for AI generated code you don't nearly understand as well as the human variety.

It seems many still favor store based reactivity state in frontend frameworks.

I contribute to it being the default so why change and because libraries like xstate are far more difficult to learn the syntax and are more verbose. But with AI that's hardly an issue, so I wonder if there is more to it I don't see and we just haven't seen the state chart reach it's peak yet.

davidkpiano

The next version of XState will be much more ergonomic, with a reduced API surface area, lower learning curve, and much easier for devs (and agents) to author.

But at the same time, frontier models are very good at writing XState.

brandensilva

I am looking forward to seeing it!

It feels bad because I know your team was working so hard pre AI to make state machines more accessible and bring such a powerful concept to the world.

I know it didn't pan out exactly, but I really want durable execution state machines that exceed workflows one day.

I keep thinking to myself can I enforce my AI layer to have some deterministic durable state machine running it and I'm not deep enough on them from a creator/author perspective to answer that question like you, but keep us posted on the changes.

ciarcode

Well, this is used in the automotive domain for long time now. Look at matlab/simulink: you can draw your algorithm as a state machine and generate the code out of it. Recently I implemented a state machine to manage a quite complex react component, who moves from one visual state to another through some css transitions. It’s not a difficult state machine, but I think people are not so well versed in it.

renticulous

I assume game engines might already have this or sophisticated version of this already implemented.

fmbb

Sure. State machines are often useful.

A general framework is I think more rarely useful.

Unreal Engine is a popular game engine and it seems to contain dozens of different state machine frameworks.

MeteorMarc

The title contains hierarchical, which does not come back in the post. You probably need hierarchy, otherwise state charts become unweildingly large.

embedding-shape

A statechart without hierarchy is just a state machine. It's the composition and hierarchy that turns a state machine into a statechart.

knollimar

Is the very first example not one without hierarchy and thus just a state machine?

embedding-shape

Technically yes, that's just a state machine. On https://statecharts.dev/what-is-a-state-machine.html the website itself also admits that that example is a "simple state machine", and on https://statecharts.dev/what-is-a-statechart.html you get the better explanation with

> A statechart is a state machine where each state in the state machine may define its own subordinate state machines, called substates

codethief

It does if you click on "What is a statechart?", https://statecharts.dev/what-is-a-statechart.html .

> The primary feature of statecharts is that states can be organized in a hierarchy: A statechart is a state machine where each state in the state machine may define its own subordinate state machines, called substates. Those states can again define substates.

sghiassy

One of my favorite data structures

Created StateKit for ObjC/Swift some time ago, it’s been production tested in some very large apps: https://github.com/sghiassy/StateKit

Such a cool data structure

neilv

A long time ago, I wrote a compiler from a curly-brace encoding of Statecharts, to Java.

More recently, I avoided some early SwiftUI bugs by modeling some of the iOS app interaction using Statecharts, in an ASCII art comment in the code, and implementing that.

jose_zap

We have been using statecharts at our company for all business processes after I wrote an interpreter for them inside Postgres.

It has been a great experience so darn it makes processes very resilient against change and very easy to come back to after years.

The library is open source too:

https://github.com/kronor-io/statecharts

dflock

I've tried to use state charts for frontend development a couple of times, but bounced off. IIRC, I was using xstate with vue, and I found that they were hard to retrofit to existing systems, and where I tried, I found that the boundary between the part of the system controlled by xstate and the rest of the system problematic. It felt like it would work better with everything "inside" the statechart, but that's a big lift for an existing codebase.

rekrsiv

Out of curiosity, was that before or after LLM agents?

dflock

Before. I could, probably, now get an LLM to refactor everything to be inside the statechart - but I'm not sure if I actually want that.

Daily Digest email

Get the top HN stories in your inbox every day.