跪拜 Guibai
← Back to the summary

Origami Agent for Rokid Glasses: Let the Fold Stay in Front of Your Eyes

Holding paper in hand, who pauses the video? I stuffed an origami teacher into AI glasses.

Last time I finished making the self-introduction practice partner "Speak Clearly", I made another agent for Rokid AI glasses, named "Origami", and it is now live.

Image

I really like making parent-child related agents. Take a piece of paper, parent and child fold a plane or a little fish together, and after folding you can play with it. That kind of thing suits me. Technically it can be fine-tuned a lot, but what I hand over to everyone, I want to be simple.

Origami has a very specific annoyance: your eyes understand, but your hands haven't caught up. You hold the paper to pause the video, come back, and forget which side you were supposed to fold. I want the glasses to keep the current fold in front of you; if you didn't see it clearly, keep looking, and when the person says "next step", then move to the next action.

This article continues the development process. I split the course, animation, voice, and model parts, and show key code.

Image

1. First think about how parents play with children

My intended usage: a parent wears the glasses to watch the demonstration, holds their own paper, demonstrates, and the child folds alongside. When both are ready, move to the next step. It's normal for a child to want to watch a few more times, or slowly press down a corner; the tutorial doesn't need to rush them.

Sometimes a parent wants to play with the child for a while but can't think of something on the spot. After a meal or in a gap before going out, take two sheets of paper, one for each, and make a small thing together. When the child is stuck, point to the crease and let them try again. That's when I hope it comes in handy.

The child chooses the project they want first; the parent can ask, "Do you think the two edges are aligned?", wait for the child to align and flatten, then decide to continue. This echoes the guided-play research that discusses child choice, timely adult hints, and clear activity goals. I want the glasses to keep the demonstration here, so the two people communicate around the paper in hand.

So the home page shows works first; after selecting, you see the finished product and paper requirements, then confirm to start. The paper plane needs A4 rectangular paper; the little fish, bookmark, and other courses use square paper. Don't discover mid-fold that you grabbed the wrong paper.

Image

The paper in the UI is outlined with green lines, dashed lines for creases, and arrows for movement direction. On the small screen there's limited space for the paper; I'd rather enlarge the action and leave long explanations to voice and necessary short hints.

Courses include paper plane, cootie catcher, jumping frog, talking puppy, paper cup, paper popper, page-corner bookmark, little fish, and little sailboat. When choosing these works, I think one step further: how can it be played after folding? The plane can be test-flown, the bookmark can be clipped into a picture book, the cup can be used for a mini basketball game. The time spent folding can also become play time together.

For the first time, choose from page-corner bookmark, little fish, or little sailboat, all split into 5 steps. Set aside 2-5 minutes for this small activity; if stuck, watch a bit more. This time is a suggestion for starting the activity; how long actual folding takes depends on proficiency and how many times you review.

When folding, one hand holds the paper, the other aligns edges and presses creases; look at one fold, do it, then compare with the paper shape; hands and eyes work together. Harvard Center on the Developing Child's play guide also treats play as an opportunity to practice focus, memory, and self-control; specific activities still depend on the child's needs.

Whether the child is willing to choose another project and can point out "I did this step myself" after folding is more concrete than a list of skill development. For me, first make this hands-on time worth repeating; long-term changes still need to be observed through later experience.

An early prototype tried photographing to judge paper shape. After a small corner was folded to the back, the model repeatedly still judged it as the previous step. The later follow-along version handed completion confirmation to the user, focusing on making the action demonstration clear.

Image

2. Split the engineering on the platform

The development entry remains AIUI Studio. After creating a new agent, you can build the project via "conversation creation", then switch to the code page to edit. For this type of project, I write down the interaction order first, like the reusable example below:

Create a parent-child origami agent "Origami".
First choose a work, see the finished product and paper requirements, then confirm start by voice.
The current fold loops and demonstrates; only when the user says next step does it switch.
Support previous step, replay, slower, and back to home.
The model combines the course and current step to explain doubts, not invent new tutorials.
Use Canvas to draw simple green-line origami animation.

Once there's a page that opens, split the course data and drawing logic out. The main files of this implementation are:

app.json                 pages and permissions
app.js                   lifecycle
lib/fold.js              courses, commands, model
lib/draw.js              geometry and drawing
pages/index/index.ink    state and events

This way, changing a voice prompt doesn't require searching through a big chunk of drawing code; when checking a fold, you can directly find the corresponding course and animation.

The page splits state into home selection, finished preview, follow-along, and completion. Course ID and step index are stored separately; the UI numbers, animations, and explanations all read from this state. For example, in step 2 of the paper popper, the screen cannot play step 2 while sending step 1 to the model. Centralizing state lets you check the work and number first when debugging.

The code below is from the kept 1.14.2 single-sheet follow-along implementation, arranged by reading order, sharing page state.

Image

app.json declares page paths and recording permission; key config below. This follow-along implementation doesn't need photos, progress is user-controlled.

{
  "name": "Origami",
  "permissions": ["RECORD_AUDIO"],
  "pages": ["pages/index/index"],
  "window": { "navigationBarTitleText": "Origami" }
}

index.ink holds page logic, the main visual is a canvas:

<page>
  <canvas id="foldCanvas" width="480" height="352"
          class="full"></canvas>
</page>

After the canvas is ready, use wx.createCanvasContext('foldCanvas') to get the drawing context, loop draw the current step and flush(). 480×352 is the canvas size for this page; course coordinates are stored separately and converted to screen position when drawing.

Each frame recomputes animation positions, then hands the current course, number, and phase to the drawing function. After omitting logging, the main loop is as follows, _epoch is the start time of this step:

const frame = () => {
  if (!this._alive) return;
  const elapsed = Date.now() - this._epoch;
  const loop = lessonLoop(elapsed, this._slow,
    this._lesson, this._index);
  render(this._canvas, {
    lesson: this._lesson, mode: this._phase,
    index: this._index, phase: loop.phase, elapsed,
    galleryIndex: this._galleryIndex
  });
  this._canvas.flush();
  this._raf = requestAnimationFrame(frame);
};
this._raf = requestAnimationFrame(frame);

3. Write a "fold" as checkable data

If you only store a start image and an end image, how to get there is vague. I put the explanation and paper data together: which part is fixed, which part folds, around which crease line, and what it looks like after folding.

For example, step 1 of the paper plane "fold left and right to make the center line", the text and crease fields are excerpted below, paper polygon coordinates omitted:

{
  title: 'fold left and right to make center line',
  detail: 'align the left long edge with the right long edge, press the center line',
  hint: 'paper is vertical; fold left-right, not top-bottom',
  crease: [[0, 0], [0, 1.4142135623730951]],
  mode: 'fold',
  tip: [-0.5, 0]
}

In the full data, base is the fixed paper, moving is the moving paper, after stores the folded shape. This example normalizes paper width to 1, long edge about 1.414, which is the aspect ratio of A4 paper. When the screen size changes, the crease and paper corners still maintain relative positions.

The fold calculation first finds the projection of a point on the paper onto the crease line, then moves it around the crease. The 2D projection function in the project is:

export const reflect = (p, a, b, t = 1) => {
  const dx = b[0] - a[0], dy = b[1] - a[1];
  const q = ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy)
    / (dx * dx + dy * dy);
  const h = [a[0] + dx * q, a[1] + dy * q];
  const c = Math.cos(Math.PI * t);
  return [h[0] + (p[0] - h[0]) * c,
          h[1] + (p[1] - h[1]) * c];
};

t goes from 0 to 1, the point moves from one side of the crease to the other. The drawing layer adds lifted paper height, front-back occlusion, and layer order; flip, unfold, four corners to center each have their own handling. It is a geometric schematic for teaching, showing creases, direction, and paper layer relationships.

Image

This effort is necessary. The same sentence "fold the top corner down", looking only at the result image, the reader might flip the whole paper or fold only one layer. The animation must distinguish the moving part from the fixed part, and the text must say "flip the whole sheet" or "fold only this layer".

4. Animation loop, step waits for the person

Each fold has three time segments: first stop at the start, then play the action, finally stop at the result. After watching once, it loops from the beginning, the current step number stays unchanged.

Different actions need different times. A single fold of the paper plane is short; the cootie catcher's "fold four corners to center" requires watching four corners consecutively, can't share a rushed duration. The project configures action times for each course:

export function lessonLoop(ms, slow, lesson, index) {
  const moveMs = COURSE_MOVE_MS[lesson?.kind];
  if (!moveMs) return loopPhase(ms, slow);
  const start = 750;
  const move = moveMs[index] * (slow ? 1.55 : 1);
  const duration = start + move + 2600;
  return {
    phase: Math.max(0, Math.min(1,
      (ms % duration - start) / move)),
    cycle: Math.floor(ms / duration),
    duration
  };
}

ms is time since entering this step, phase decides how far the fold is in this frame. "Slower" stretches the action segment to 1.55 times, still pausing at start and result. Looping only computes animation positions; switching steps goes through a separate command branch:

if (c === 'next' && p === 'learning') {
  if (this._index < l.steps.length - 1) {
    this._index++;
    return this._screen('user-next');
  }
  return this._beginCompletion('last-step-done');
}

Here c is the parsed command, p is current page phase, l is the selected course. Only when "next" is received does the number increase; after confirming the last step, it enters the celebration page. Replay resets the animation start; previous step rewinds the course index, both without waiting for the model.

Preview and follow-along have separate entries. While the user is still viewing the finished product, wait for "confirm"; replay and slower in follow-along only refresh this step:

if (c === 'confirm' && p === 'preview') {
  this._phase = 'learning';
  this._index = 0;
  this._resume = null;
  return this._screen('confirmed');
}
if (['replay', 'slower', 'normal'].includes(c)
    && p === 'learning') {
  if (c === 'slower') this._slow = true;
  if (c === 'normal') this._slow = false;
  this._screen(c);
}

After the paper-prep hint on the preview page, it directly tells the user to say "confirm" to start. If the entry is clear, the follow-along requires less guessing.

Image

_screen at the start sets _epoch to current time and resets the loop count to -1, so replay can restart from the action start. The step index hasn't changed, the screen still shows this fold.

I care a lot about this rhythm. If the parent hasn't seen clearly, they can stay on the same fold, wait until the paper in hand matches the demonstration, then lead the child to continue.

5. The model is responsible for understanding which part

"Next step", "previous step", "watch again" are clear commands, handled directly by the program. Full names and common abbreviations of works are also matched against a local catalog first, e.g. "plane", "puppy", "popper". When a selection request exceeds fixed expressions, is ambiguous, or is a question about the current step, it goes to the model.

Matching also can't treat all sentences containing the work name as selection. "Don't want paper plane" and "paper plane or fish" both need to understand meaning first. When negation or multiple choices are unclear, the system prompt requires the model to ask first.

The context sent to the model includes the course catalog, current phase, selected work, and current step. In teaching, only explain the current fold; when the user wants to switch works, give preview first, after confirmation then start. This way "which direction does this corner fold" isn't misinterpreted as done.

Expanding the context construction in modelPrompt, the main information can be organized as follows:

const step = lesson && phase === 'learning'
  ? lesson.steps[index] : null;
const prompt = JSON.stringify({
  catalog: LESSONS.map(l => ({
    id: l.id, name: l.name, paper: l.paper,
    aliases: l.aliases || []
  })),
  phase,
  currentLesson: lesson ? lesson.name : null,
  currentStep: step ? {
    number: index + 1, title: step.title,
    detail: step.detail, hint: step.hint
  } : null,
  user: text
});

The call uses the platform's built-in LanguageModel. The session call and return validation are shown together; the full page also handles timeout and request cancellation:

import { LanguageModel } from 'language-model';

if (await LanguageModel.availability()
    !== 'available') {
  throw Error('model not connected');
}
const session = await LanguageModel.create({
  initialPrompts: [
    { role: 'system', content: SYSTEM }
  ]
});
try {
  const raw = await session.prompt(prompt);
  const reply = validateReply(raw);
  // handle result as select, help, or unsupported
} finally {
  session.destroy();
}

The return value is agreed as kind, lessonId, reply. select can only select existing courses, help only shows explanations, unsupported says it's not supported. The program checks whether the work ID exists, whether the reply is empty, whether the text is too long, then updates the page. The model cannot make up a tutorial without animation.

Below is the main body of return validation. Code fences are stripped first, compatible with the model wrapping an extra response layer, then checks allowed types and courses:

const parsed = JSON.parse(String(raw).trim()
  .replace(/^```(?:json)?\s*/, '')
  .replace(/\s*```$/, ''));
const x = parsed && parsed.response
  && typeof parsed.response === 'object'
  ? parsed.response : parsed;
if (!x || !['select', 'help',
    'unsupported'].includes(x.kind)
    || !(x.lessonId === null
      || getLesson(x.lessonId))
    || typeof x.reply !== 'string'
    || !x.reply.trim()
    || x.reply.length > 150) {
  throw Error('model reply format incomplete');
}
if (x.kind === 'select' && !getLesson(x.lessonId)) {
  throw Error('this work doesn't have complete animation');
}

In earlier development records, input "I want to fold a little fish" made the model return kind: select and lessonId: fish, the page then entered fish preview. After adding local name matching, such explicit requests can be selected directly, leaving the model for expressions that need more understanding.

Image

Another type of test is asking for direction at a certain step. In an early puppy course, asking "does this step fold to the back?", the model explained the top small corner should fold to the back, and the page stayed on the original step. Here the course and question are passed in; there's no photo of the user's paper, so it can't answer "I see you folded correctly".

A real model return from a little sailboat test was:

{
  "kind": "select",
  "lessonId": "sailboat",
  "reply": "OK, let's make a little sailboat. Please prepare a square piece of paper and fold it into a triangle to start."
}

When the return is applied to the page, selecting the course and displaying the explanation are handled separately:

const r = validateReply(await this._model(prompt, gen));
if (gen !== this._gen || !this._alive) return;
if (r.kind === 'select') {
  this._previewLesson(
    getLesson(r.lessonId), 'model-select');
} else {
  this.setData({ hint: r.reply });
  this._speak(r.reply);
}

_previewLesson resets this course's index and enters preview. After the user confirms, _screen reads the first step explanation from the course. The model selects the work but doesn't get permission to rewrite the animation steps.

Image

6. Connect voice and temple-arm operations

Speech recognition uses the final result; interim recognized text doesn't drive steps. The recognition instance also needs deduplication to avoid the same "next step" being consumed twice. The result handling branch:

const rec = new SpeechRecognition();
const done = new Set();
rec.lang = 'zh-CN';
rec.continuous = true;
rec.interimResults = true;
rec.onresult = e => {
  for (let i = e.resultIndex;
       i < e.results.length; i++) {
    const r = e.results[i];
    if (!r || !r[0] || !r.isFinal
        || done.has(i)) continue;
    done.add(i);
    const text = String(r[0].transcript).trim();
    if (text) this._handle(text, 'speech');
  }
};

done is a set for the current recognition instance; after recognition ends, only if still in listening state is it restarted. On leaving the page, animation, recognition, voice playback, and model session are all cleaned up. Async replies must also check the current request number, to avoid an old explanation covering the page after the user has switched works.

Temple-arm operations also enter the same handling entry. The main branch of the press event is kept below; _keyAt is initialized to 0 on the page, repeated events within 180 milliseconds are ignored:

if (['Enter', 'ArrowDown', 'ArrowUp']
    .includes(e.code)) {
  if (typeof e.preventDefault === 'function') {
    e.preventDefault();
  }
  if (Date.now() - this._keyAt < 180) return;
  this._keyAt = Date.now();
  if (e.code === 'Enter') this.toggleVoice();
  else this._handle(e.code === 'ArrowDown'
    ? 'next step' : 'previous step', 'temple');
}

The model wait limit is 30 seconds; on failure, the current step is kept. If the user issues an explicit command during the wait, the old task is cancelled and this operation executes. So when you just want to go back to see the previous fold, you don't need to wait for an explanation to finish generating. The animation is always refreshed by its own loop, so it doesn't stop waiting for the model.

7. After testing, hand the work out

During testing, I go through selection, preview, confirm, loop, review, and completion. I also specifically stop on the first fold and watch it several times, checking it doesn't secretly skip steps; after asking questions, check the number; when switching works and cancelling, check whether it can return to the original progress.

The simulator can submit speech recognition text, suitable for checking how commands and model results affect the page. The interface images in this article are from simulator screenshots kept during development; actual wearing, real recording, and parent-child follow-along effects need separate experiences.

For future family experiences, I want to record the time of joint hands-on, how many steps the child folded independently, whether they can continue after getting stuck, and whether they'd like to play another one. To compare phone vs glasses, I'd need to cross-balance the order of experiences to avoid counting the second time's familiarity as a device advantage; this part is currently a plan.

Image

After it runs on the platform, fill in basic info, package AIX, prepare screenshots and demo video consistent with this version, then submit for review. "Origami" already has a published version; I continue updating courses. Friends with Rokid glasses are welcome to try it, starting from one you want to fold.

Image

When making this agent, the most worthwhile things to repeatedly tweak are often very small: when this corner isn't clear, the animation pauses more; when you want to rewatch, don't make people start from the beginning; when the paper isn't ready, don't start.

In the future I still want to make more parent-child agents, gradually building things that can be done hands-on and played with together. If you like this direction, follow me. Also tell me what you want to fold with your child next time.

Image

I'm Xiaoyu, welcome to try "Origami", see you at the next work.