0

I wrote an AppleScript to synch my Reminders (via export to JSON). It runs great... from the Script Editor. As soon as I tried to run it on the command line via osascript, I discovered it hits a wall when it tries to access reminders. After maybe a minute and a half, I get this error:

/Users/robleach/Temporary/synchRemindersTest.scpt: execution error: Reminders got an error: AppleEvent timed out. (-1712)

I also noted these errors in the console:

error   19:33:49.628309-0400    tccd    Refusing client without path (from responsibility_get_responsible_audit_token_for_audit_token) PID[1422]: (#3) No such process
error   19:33:49.628370-0400    tccd    Refusing TCCAccessRequest for service kTCCServiceReminders from invalid client with pid 1422

Assuming it was a permissions issue, I looked in System Preferences>Security & Privacy>Reminders, and noted that osascript is not there, nor do I have ± buttons to add it, even after authenticating.

I wondered whether saving the script as an app would prompt the Security stuff to prompt me to enable it - and that I could cron the opening of that app, but if I do that, I won't be able to pass arguments to the script (or at least, I don't know how to do that). Plus, I'd rather everything happen in the background, without a dock icon or anything (aside from the Reminders app needing to be open).

I wrote a toy example of the script that produces the timeout error:

TOY 1

tell application "Reminders"
    return (properties of every reminder whose completed is false)
end tell

And I call it like this:

> osascript /Users/robleach/Temporary/synchRemindersTest.scpt

Is there a way to allow the osascript run of the script to be allowed access to the reminders? Could I like code-sign the command line executable or something? If I were to write this in another language, would it have the same issue?

I'm running Catalina 10.15.7.

UPDATE 1

I dug some more into the console. There are number of other, potentially relevant errors. I think it actually is a timeout. When I run it in Script Editor, it runs in about 40 seconds, but it times out when I run it via osascript (at maybe around a minute and a half).

However, I recalled that I have another script on a cron job that accesses reminders, and I did not remember it having an issue. So I tested it, and for whatever reason, it executes a very similar command, but succeeds. And it runs much faster in the Editor than it does on the command line from osascript. I pulled that one line out of that script that succeeds and wrapped it in a toy script:

TOY 2

tell application "Reminders"
    set theList to "ToDo Home Recurring"
    set namesDates to {name, due date} of (every reminder in list theList whose completed is false)
    display dialog "Got " & (count of namesDates) & " reminder names & dates"
end tell

and it failed via osascript with the same timeout error. Then I pulled out another line and added it to the toy:

TOY 3

tell application "Reminders"
    set theList to "ToDo Home Recurring"
    show list theList
    delay 0.25
    set namesDates to {name, due date} of (every reminder in list theList whose completed is false)
    tell application "System Events" to display dialog "Got " & (count of namesDates) & " reminder names & dates"
end tell

...it succeeds. So I don't think this is a permissions issue any longer. This feels like it maybe has to do with how efficiently osascript accesses Reminders.

I also started noticing that my first toy example above sometimes fails when run from the script editor. I kept retrying it to get the running time I pasted above and I started to sense a pattern. I think that when I select a new list to view in the Reminders GUI (it doesn't matter which one), then run the script (from the editor), it works. But if I don't select a new list to view and run the script from the editor again, it fails with that timeout.

...but that seems nuts. Can anyone explain what's going on here?

NOTE: The script I'm writing is actually an AppleScript re-write of a Siri Shortcut I wrote (that runs reliably in around 25ish seconds). Since I wanted to automate it and run it more than once a day, I decided to use AppleScript.

UPDATE 2

I tried the answer suggested by @Robert Kniazidis.

TOY 4 (modification of TOY 1)

with timeout of 3600 seconds
    tell application "Reminders"
        set allRems to (properties of every reminder whose completed is false)
        display dialog "Got " & (count of allRems) & " reminders"
    end tell
end timeout

...and kept a closer watch on the console.

Attempt 1 (TOY 4)

I ran TOY 4, starting at 7:25:24, for 10 minutes, then control-c'd it. I immediately saw numerous errors in the console. I searched the console for "Reminders" and here's what I go during the run.

Attempt 2 (TOY 4)

Then, given my insights regarding my annecdotal successes when I click a list name in the Reminders GUI, I tried clicking on a random list and ran TOY 4 again immediately after. I started TOY 4 at 7:38:23. At 7:44:22, it succeeded! That's about 6 minutes!

The console had many fewer messages in it, none of them marked as error. For comparison's sake, here are the console results from searching for "Reminders".

Discussion

I have revised my theory about what's happening. Given the console messages, I infer that when you run by osascript from the command line, the script is identified as "indirect access", and as such, is subject to a higher level of security-scrutiny, thus is takes much longer to execute. Perhaps when I "click in the GUI" (or even via AppleScript, show list theList), the security concern is still considered "indirect", but is not totally unknown to the user because the GUI is changing, so is subject to somewhat less scrutiny, and thus takes 6 minutes as opposed to somewhere over 10 minutes.

If that's true, it is interesting to note that that lesser level of scrutiny is applied even if the Reminders GUI is on a different desktop (as has been the case in my tests*).

UPDATE 3

I tried ad-hoc code-signing this morning with:

codesign --force -v -s - synchRemindersTest.app/Contents/Info.plist synchRemindersTest.app/Contents/PkgInfo synchRemindersTest.app/Contents/Resources/applet.rsrc synchRemindersTest.app/Contents/Resources/Scripts/main.scpt synchRemindersTest.app/Contents/Resources/applet.icns

...and ran the app again, which was a version of TOY 1. Still got the timeout error. I was hoping it would take 40s, like when run from the script editor. When I get time, I'll try it again but manually select a list in the Reminders GUI.

UPDATE 4

I ran the same toy as in update 3 again just now. For the 2 minutes it ran before the timeout, the console was filled with 52,349 lines of mostly this, repeating over and over, which is only the portion of that timespan that matched the search term tccd.

I also have noted that the same unmodified script, run at different times, will succeed in some runs and fail on others. Such as:

TOY 5 (synchRemindersTest5.scpt)

with timeout of 600 seconds
    tell application "Reminders"
        show list "ToDo Home"
        set startt to (get current date)
        set allRems to (properties of every reminder whose completed is false)
        set endt to (get current date)
        set dur to (endt - startt)
        set msg to "Got " & (count of allRems) & " reminders in " & dur & " seconds"
        tell application "System Events" to display dialog msg giving up after 5
        return msg
    end tell
end timeout

I ran it repeatedly yesterday, successfully, but I get the timeout when I run it today:

[Jun 08 22:59:51]:~/GoogleDrive/Scripts>osascript synchRemindersTest5.scpt
Got 166 reminders in 287 seconds
[Jun 08 23:06:17]:~/GoogleDrive/Scripts>osascript synchRemindersTest5.scpt
Got 166 reminders in 291 seconds
[Jun 08 23:11:45]:~/GoogleDrive/Scripts>osascript synchRemindersTest5.scpt
Got 166 reminders in 293 seconds
[Jun 08 23:17:46]:~/GoogleDrive/Scripts>osascript synchRemindersTest5.scpt
Got 166 reminders in 300 seconds
[Jun 09 8:23:28]:~/GoogleDrive/Scripts>osascript synchRemindersTest5.scpt
synchRemindersTest5.scpt: execution error: Reminders got an error: AppleEvent timed out. (-1712)

Footnotes

* I've been testing my scripts intentionally with the Reminders app on a different desktop because I have noted in my efforts that GUI scripting is always faster than accessing via the Reminders dictionary. So I wrote 2 methods: GUI and Reminders Dict. The GUI one will run if the open Reminders app is on the desktop (which I keep tucked under the dock). If we're watching Netflix full screen, I have a try/catch to use the slower Reminders Dict access method when the GUI is, as in that case, on a different desktop.

hepcat72
  • 890
  • 4
  • 22
  • RE: `set theList to "ToDo Home Recurring"` -- `theList` in this case is not a _list_, it's just a _string_. BTW I have no problems with your first "toy example", in **Script Editor** or using `osascript`, but haven't tried the one in the update. Tested under **macOS Catalina** 10.15.7. – user3439894 Jun 07 '21 at 01:36
  • I am not surprised it works for you. I have encountered issues before with Reminders scripts and people have said that there can be issues when you have lots of reminders. I currently have maybe a dozen lists and 201 "un"-complete reminders and probably loads of completed ones. I use it for everything. The annoying thing is that Siri Shortcuts has no issue with the size of my reminders content. – hepcat72 Jun 07 '21 at 01:43
  • Incidentally, by `theList`, I mean `theNameOfTheList`. So the variable is a bit of a misnomer. – hepcat72 Jun 07 '21 at 11:47
  • Quick note. I think this may be the key to the answer: https://derflounder.wordpress.com/2018/08/31/creating-privacy-preferences-policy-control-profiles-for-macos/ – hepcat72 Jun 07 '21 at 14:13
  • Have you considered rewriting your script as a script application. That avoids any osascript problems, and allows you to control the security status of the script app directly. You can then run that from cron (or launchd; cron earns a solid wtf?), or set it up as a stay-open app that runs independently. If that seems like something you might want, I'll write an answer showing how. – Ted Wrigley Jun 07 '21 at 14:57
  • If you mean save the script as an app, I did try that & got the same err. If you mean code changes, I'm clueless as to what would have to change in the code. But I assume saving as an application though is what you mean? WRT cron versus launchd, i'm not very familiar w/ launchd, but I assume that you're inferring that my script is a constantly running daemon? All it is, is a retrieval and conversion to JSON. It grabs all uncompleted and modified reminders since the last retrieval & overwrites the prev JSON file (including prev & current run times to use them in the logic of automations). – hepcat72 Jun 07 '21 at 15:09
  • 1
    @hepcat72: It helps if you use the '@' tags, like I did here; that way I'm notified when you reply. On MacOS launchd is the central process for launching everything; cron is considered legacy. And I'm aware that you're running a periodic task; I'm merely suggesting that you can design a background app that handles it's own periodic invocation instead of relying on cron or launchd to run it. If you save the script as an app and run the app directly (by double-clicking it) do you still get the time lag and/or error? – Ted Wrigley Jun 07 '21 at 15:24
  • @Ted Wrigley: Sorry, I often forget to tag. I did test an app version of `TOY 1` and got the error. Based on my current hypothesis, that suggests it's still deemed as "indirect access". According to https://derflounder.wordpress.com/2018/08/31/creating-privacy-preferences-policy-control-profiles-for-macos/ , it suggests the app needs to be code-signed. – hepcat72 Jun 07 '21 at 15:34
  • I also found this thread which suggests running the script via Keyboard Maestro (albeit in an earlier OS) potentially works around the indirect access issue and avoids timeouts. That's still manual triggers, but I wonder if a script that performs a keyboard shortcut keystroke would also work as a work-around... https://talk.automators.fm/t/not-authorized-to-send-apple-events-to-mail/8980/9 – hepcat72 Jun 07 '21 at 15:42
  • @Ted Wrigley: I should have mentioned that when I tried the app version of `TOY 1`, I'd added it to Security&Privacy>Privacy>Reminders. @Robert Kniazidis's latest answer reminded me I did that before that test. I guess the next test would be to code-sign that app. I've code-signed a couple apps before in the past, so I'll give it a shot when I get a chance. – hepcat72 Jun 07 '21 at 16:21
  • @hepcat72: well, at this point I'd be tempted to change approaches and loop through the reminders rather than trying to retrieve them all at once. In other words, start with `repeat with thisRem in every reminder whose completed is false` and then do what you need to do with each `thisRem` in turn. It won't make things faster, but it might avoid the timeout problem since it's pulling data sequentially, not all at once. – Ted Wrigley Jun 09 '21 at 04:46
  • You know, I'd tried that in my first reminder script (the one that currently runs well) and the all-retrieval actually runs reasonably well. I had another idea last night though that is a changed approach. Instead of getting all incomplete and modified reminders every time, I could grab all incomplete once and then from then on, only grab modified. I'll try the modified version today and see if it runs well. I'll have to modify the way I'm saving the json though if it works. – hepcat72 Jun 09 '21 at 11:21

3 Answers3

0

Wrap your script with timeout of 3600 seconds (1 hour). Your script time outs with default time = 2 minutes (120 seconds) per command. So,:

with timeout of 3600 seconds -- or 600 seconds, or as you want
    tell application "Reminders"
        return (properties of every reminder whose completed is false)
    end tell
end timeout
Robert Kniazidis
  • 1,760
  • 1
  • 7
  • 8
  • I'll give this a try. Why do you think that the script takes 40 seconds when run via script editor? I mean, sometimes I hit the timeout in script editor too. It's so inconsistent. – hepcat72 Jun 07 '21 at 10:38
  • But the first toy example always times out when run via osascript. – hepcat72 Jun 07 '21 at 10:40
  • I added `UPDATE 2` to my question. Your suggestion has helped illuminate more of what is going on and may lead to a reliable solution. I have anecdotal evidence that *maybe* clicking a Reminders list or using the `show list listName` command in the script *may* indirectly make the code execute faster, possibly due to fewer security checks on the transactions... – hepcat72 Jun 07 '21 at 13:02
0

Seing your TOY 4 once again. Man page of osascript says: Any arguments following the script will be passed as a list of strings to the direct parameter of the ``run'' handler. So, your TOY 4 should be like this:

on run argv -- THIS
    with timeout of 3600 seconds
        tell application "Reminders"
            set allRems to (properties of every reminder whose completed is false)
            display dialog "Got " & (count of allRems) & " reminders"
        end tell
    end timeout
end run -- and THIS

I tried this script in the Terminal, using following command, and it successfully asked for access to Reminders, and worked after access granting. Note quotes as well:

osascript '/Users/123/Desktop/synchRemindersTest.scpt' 'output.json' 'Reminders' 'ToDo'
Robert Kniazidis
  • 1,760
  • 1
  • 7
  • 8
  • My toy doesn't use the input (though my example shows input in the command). Sorry for the confusion. I've been running the toy examples without input. The input isn't the problem. It's the size of my reminders DB, and I suspect, the combination of that with the slowness of "indirect access" – hepcat72 Jun 08 '21 at 19:34
  • OK, in what form you tried osascript command in the Terminal? You say at title: **(with arguments)**. With arguments you should put **on run argv** explicit. But my osascript tests worked with script version without arguments as well. Quotes syntax is important as well. – Robert Kniazidis Jun 08 '21 at 19:48
  • I'm aware. I have many scripts that take and use argv on the command line and I have been running tests of the toys without command line arguments. Sorry for the confusion. When I pasted the command line call in the issue, I was confusingly giving an example of the original script, not the toys. That was dumb. If the concern is a missing argv in the `on run` line, then why would the toys ever succeed in the instances I have outlined? – hepcat72 Jun 08 '21 at 20:45
  • I just checked my Reminders DB. I currently have 192 incomplete reminders and 9,534 completed reminders. So I'm not surprised you run the TOY examples without issue. I suspect that deleting a ton of reminders would work around the issue, but I can't just blindly delete reminders. I often manually "un-complete" reminders, e.g. grocery list items and a packing checklist. I consider them like "manually recurring" items. There's also no way to archive items - and I like to be able to see when I completed something, or what a phone number or email was in an old reminder, or an attached image... – hepcat72 Jun 08 '21 at 21:59
  • So the issue, to me, is the fact that Script editor runs relatively quickly, but osascript (due to `tccd` identifying it as "indirect access") causes it to run orders of magnitude slower. – hepcat72 Jun 08 '21 at 22:02
0

I did not figure out exactly what was causing the issues, but I repeatedly tried the same exact code with varying results/behaviors, apparently depending on various circumstances. Here are my observations.

Using any of the toy examples, there were 2 running behaviors that seemed to change:

  • runtime (fastest I could get was near half a minute, but the same code could take over 10 minutes in certain cases - I control-c'd them, so I don't know how long they'd have run)
  • tccd and other errors in the console (having to do with Apple's mechanism for "transparency, consent, & control" - i.e. the thing that makes those access request popups happen)

I tried running the toy examples above in the following ways:

  • From Script Editor
  • Via osascript from the command line
  • Rewritten as Javascript for Automation (aka "JXA") (from script editor)
  • As an app, double-clicked
  • As an app opened from the command line

And I ran those various methods under the following various circumstances (where possible):

  • Immediately after unlocking the screen
  • With the Reminders App open on the current desktop
  • With the Reminders App open off the current desktop
  • Without manually interacting with the Reminders GUI prior to running
  • With manually interacting with the Reminders GUI prior to running
  • With including an applescript instruction to show a list in the Reminders GUI
  • Without including an applescript instruction to show a list in the Reminders GUI

And there's one other important factor to take into account:

  • Reminders database size

Apple doesn't actually ever delete anything from the reminders database. I currently have 9,604 completed reminders and 193 incomplete reminders. While exploring this issue, I discovered reminders over a decade old in my reminders database.

I suspect that the issues have more to do with the size of the database than the tccd errors, as I found threads on the Apple Developers forum that describe those errors as mere log noise. I also found posts by developers who note that the ever growing size of the reminders database leads to growing performance issues, and noted that there's no way to really delete entries. Deleted entries are simply labeled as deleted.

I have found that there is no reliable running context that runs both fast and without errors under every circumstance (when you have a large Reminders database). All the ways of executing fail under certain circumstances. Some cases run faster than others, but none ever run in what I would consider a reasonable running time.

I tried code-signing an app version of the toy scripts, explicitly granting entitlements to the reminders data, but according to an app called Taccy, while I could retrieve those entitlements from the files to which they were applied, they did not prevent the tccd errors or make any of the cases run faster. I even tried code-signing a copy of the osascript executable, but apparently it only works for app bundles.

While I could see a difference in runtime under certain circumstances and could avoid tccd errors by doing things in a certain way in some circumstances (all seemingly requiring true manual actions), the runtimes were never significantly improved and errors/failures seemed unavoidable in cases where for example, the screen was locked.

So I concluded that given the size of my reminders database and the fact that I wanted to run this script with the screen locked (e.g. on a cron job), I had to abandon an AppleScript solution. It's impossible to do it predictably & reliably. (I had briefly explored a Siri Automation on an iOS device, but discovered the hoops to jump through to get it to run more than once a day were too annoying.)

So remembering that reminders were(/used to be) stored as ics files in the Library folder. I learned that with the Reminders update in iOS 13 & macOS Catalina, storage of reminders had moved to an sqlite database under ~/Library/Reminders/Container_v1/Stores.

I poked around in the database last night and started to figure things out. I googled some of what I found and found a single google hit to a github repo that had already worked the difficult sqlite stuff out. I ended up with a shell script that reliably retrieves all reminder data (nearly 10k records) in about 1 second!

I have yet to refine it to convert it to JSON and to additionally retrieve anything modified after a certain date, but what I have so far is sufficient to answer this question.

I wrote the shell script in the (unpopular) shell language of tcsh. Feel free to rewrite it in bash or start from the repo I found, which already is in bash (but doesn't retrieve all reminders data):

set REMINDERS_STORES="$HOME/Library/Reminders/Container_v1/Stores";
set SQL_GET_Z_ENT="SELECT Z_ENT FROM Z_PRIMARYKEY WHERE Z_NAME = 'REMCDList'";

foreach DBFILE ( "$REMINDERS_STORES"/Data-*-*.sqlite )
  set DB="file:${DBFILE}?mode=ro"
  set COUNT=`sqlite3 "$DB" "SELECT COUNT(*) FROM ZREMCDOBJECT WHERE Z_ENT = ($SQL_GET_Z_ENT) AND ZCKIDENTIFIER IS NOT NULL;"`
  if ( "$COUNT" > 0 ) then
    set REMINDERS_DB="$DB"
  endif
end

set Z_ENT_LISTS=`sqlite3 "$REMINDERS_DB" "$SQL_GET_Z_ENT;"`
set YEARZERO=`date -j -f "%Y-%m-%d %H:%M:%S %z" "2001-01-01 0:0:0 +0000" "+%s"`
set NOW=`date "+%s"`

sqlite3 "$REMINDERS_DB" "SELECT strftime('%Y-%m-%dT%H:%M:%S',($YEARZERO + TASK.ZDUEDATE),'unixepoch') as dueDate, TASK.ZPRIORITY AS priority, TASK.ZTITLE1 AS title, LIST.ZNAME1 AS list, TASK.ZNOTES AS notes, TASK.ZCOMPLETED as completed, strftime('%Y-%m-%dT%H:%M:%S',($YEARZERO + TASK.ZCOMPLETIONDATE),'unixepoch') as completionDate, strftime('%Y-%m-%dT%H:%M:%S',($YEARZERO + TASK.ZCREATIONDATE),'unixepoch') as creationDate, TASK.ZDISPLAYDATEISALLDAY as isAllday, strftime('%Y-%m-%dT%H:%M:%S',($YEARZERO + TASK.ZDISPLAYDATEDATE),'unixepoch') as alldayDate, strftime('%Y-%m-%dT%H:%M:%S',($YEARZERO + TASK.ZLASTMODIFIEDDATE),'unixepoch') as modificationDate, TASK.ZFLAGGED as flagged FROM ZREMCDOBJECT TASK LEFT JOIN ZREMCDOBJECT LIST on TASK.ZLIST = LIST.Z_PK WHERE LIST.Z_ENT = $Z_ENT_LISTS AND LIST.ZMARKEDFORDELETION = 0 AND TASK.ZMARKEDFORDELETION = 0 ORDER BY CASE WHEN TASK.ZDUEDATE IS NULL THEN 1 ELSE 0 END, TASK.ZDUEDATE, TASK.ZPRIORITY;"

Here is an example of the output:

2011-11-01T18:30:00|0|Pay the rent|ToDo Home Recurring||1|2011-11-03T13:21:00|2017-09-18T16:59:00|0|2011-11-01T22:30:00|2020-01-04T20:40:00|0
2011-11-05T15:45:00|0|Feed meter|Reminders||1|2011-11-06T15:39:00|2017-09-18T16:59:00|0|2011-11-05T19:45:00|2020-01-04T20:36:00|0

Note, to get the dates in your time zone, as opposed to GMT(/UTC?), append 'localtime', e.g.:

strftime('%Y-%m-%dT%H:%M:%S',($YEARZERO + TASK.ZDUEDATE),'unixepoch', 'localtime')
hepcat72
  • 890
  • 4
  • 22